I have the following html
<label>
outer
<span>inner</span>
</label>
I want to replace the 'outer' value, leaving the span with its 'inner' text intact. Using
$('label').text('new outer');
replaces the entire content of the label (along with the span). Is there a nifty way to only select the text block 'outer' without adding extra spans or doing advanced stuff like storing the value of the label's inner span and then reapplying it?
This will update just the text of the first Text node in the element, without disturbing the span (or any subsequent Text nodes):
$("label").contents().each(function() {
// Within this iterator function, jQuery sets `this` to be
// each child node (including Text nodes, not just Elements)
if (this.nodeType === 3) { // 3 = text node
this.nodeValue = "updated ";
return false;
}
});
Live example | source
And of course, you can refine that. The Text node's current text is available (of course) from node.nodeValue, so if you wanted to just modify that (perhaps replacing only certain parts of it), you can do that; or if you wanted to modify the first one that matched a given pattern, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With