Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the first-level text element '.text()' without selecting child elements

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?

like image 728
Per Hornshøj-Schierbeck Avatar asked Nov 19 '25 00:11

Per Hornshøj-Schierbeck


1 Answers

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.

like image 103
T.J. Crowder Avatar answered Nov 20 '25 14:11

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!