A. Wolff
A. Wolff

Reputation: 74420

jQuery text() method doesn't work on textnodes

jQuery text() method doesn't work on textNodes:

$('div').contents().filter(function(){
  return this.nodeType === 3;
}).text("new text");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
   textNode text doesn't change
</div>

My question is what could be the reason for that?

Is this regarding withespace text nodes hard to handle? And/or deeper level descendant text nodes than only children ones?

I'm not asking how to change it, i know workarounds but why jq text() method doesn't support text nodes? I'd expect using this method on any text node being able to change its node value.

I'm quite sure there is a good reason for that, i cannot just getting it.

Upvotes: 1

Views: 504

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074949

what could be the reason for that?

Because that's not what text is designed to do. From the docs:

...set the text contents of the matched elements

(My emphasis)

Why it's not designed to do that is a question for John Resig and/or the current set of jQuery maintainers, but at a guess, having it handle text nodes as well as elements would complicate the method. It would have to check the nodeType and set nodeValue if it were a text node, or do what it currently does (I don't know whether they do innerText/textContent or append a text node, probably the former) for an element.

Most of jQuery is element-centric, ignoring other nodes. contents is one of the very few methods that works at the node level.

Upvotes: 1

Related Questions