I\'m having trouble wrapping my head around what should be a simple solution. I want to replace text within a label tag, without affecting the other \'siblings\', if they ex
As patrick points out, you can use contents() to select the text alone, and then do a replace on it all. Adapting the example given there, you could also try:
$(".myFieldsetClass label:contains('Some Label ')").contents().filter(function() {
return this.nodeType == 3 && $(this).is(":contains('Some Label ')");
})
.replaceWith("Some Label");
However, if you know that "Some Label " will always be the last element in the <label>
then patrick's method will be faster I believe.
A one-liner:
$('.myFieldsetClass label').contents().last().remove().end().first().after('New Label')
Why not simply do an entire replace using regex?
$(".myFieldsetClass label:contains('Some Label ')")
.each(function() {
$(this).html($(this).html().replace(/Some Label ./, "Some Label"));
});
Try:
$(".myFieldsetClass label:contains('Some Label ')").contents().filter(':last-child').text("Some Label");
This should work assuming the text to be replaced will always be at the end. The contents()
function selects all nodes, including text nodes.
http://api.jquery.com/contents/
EDIT: I should have used filter() instead of find(). Corrected.
EDIT: Works now. Here's one way.
// Store proper labels in a variable for quick and accurate reference
var $labelCollection = $(".myFieldsetClass label:contains('Some Label ')");
// Call contents(), grab the last one and remove() it
$labelCollection.each(function() {
$(this).contents().last().remove()
});
// Then simply append() to the label whatever text you wanted.
$labelCollection.append('some text')