1

How can I target an element but not its nested element?

For instance, I don't want to change the text in the <span> that is nested inside <h1>

HTML:

<h1>Change me <span> Don't change me</span></h1>
<h1>Change me <span> Don't change me</span></h1>

jQuery:

$("h1:first").text('Changed');

So the result should be:

<h1>Changed <span> Don't change me</span></h1>
<h1>Change me <span> Don't change me</span></h1>
Tim Cooper
  • 151,519
  • 37
  • 317
  • 271
Run
  • 51,293
  • 159
  • 419
  • 719

2 Answers2

2

Here you go:

$( 'h1' )[0].firstChild.nodeValue = 'Changed ';

Live demo: http://jsfiddle.net/TqxrT/1/

Šime Vidas
  • 173,790
  • 60
  • 275
  • 374
  • I think this is one of those examples which proves that sometimes JavaScript is more concise than jQuery. :). +1 – Saeed Neamati Sep 17 '11 at 12:53
  • @Saeed jQuery's version is pretty short too: `$( 'h1' ).first().contents().first().replaceWith( 'Changed ' );`. Arnaud's solution is a bit longer because it explicitly searches for text nodes. In contrast, I just select the first child... – Šime Vidas Sep 17 '11 at 13:05
1
$("h1:first").contents().filter(function() {
    return this.nodeType == 3;
}).replaceWith('foo');

alert($("h1:first").html());

What it does:

Try it here: http://jsfiddle.net/CZLuN/

Arnaud Le Blanc
  • 95,062
  • 22
  • 198
  • 192
  • Was just going to post the same, guess you were faster. –  Sep 17 '11 at 12:41
  • @arnaud, great solution. I didn't know about `nodeType` property of DOM elements. – Saeed Neamati Sep 17 '11 at 12:51
  • nodeType is the type of the node (it can be an element, a document, a text node, etc). `3` is for text node. Not all browsers have constants of these, thus using the number directly. See https://developer.mozilla.org/en/nodeType – Arnaud Le Blanc Sep 17 '11 at 12:57