1

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.

0

1 Answer 1

1

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.

8
  • Wouldn't just check in text() method for nodetype textNode and then use nodeValue to set text enough simple?
    – A. Wolff
    Dec 5, 2015 at 9:49
  • @A.Wolff: Yes. Which complicates the method. Dec 5, 2015 at 9:49
  • 2
    @A.Wolff: If you want to go down the "strange" path with regard to the jQuery API, you have a long walk ahead of you. ;-) Dec 5, 2015 at 10:00
  • 1
    @A.Wolff: That part doesn't surprise me, since the method's purpose is to gather up the text of the set. text is a weird one, even for the jQuery API: All the other accessor methods (val, attr, prop, and so on) just get from the first element in the set, but text gets from all elements in the set: jsfiddle.net/uozdnb04 This is what I mean about it being a long path... Dec 5, 2015 at 10:19
  • 1
    Thanks, this is the relevant answer. I always appreciate to read your posts :)
    – A. Wolff
    Dec 6, 2015 at 13:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.