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.

A. Wolff
  • 74,033
  • 9
  • 94
  • 155

1 Answers1

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Wouldn't just check in `text()` method for nodetype textNode and then use `nodeValue` to set text enough simple? – A. Wolff Dec 05 '15 at 09:49
  • @A.Wolff: Yes. Which complicates the method. – T.J. Crowder Dec 05 '15 at 09:49
  • Ok i think this is the main reason `jQuery is element-centric` indeed. That's just quite 'strange' than a method called `text()` doesn't work on text. – A. Wolff Dec 05 '15 at 09:58
  • 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. ;-) – T.J. Crowder Dec 05 '15 at 10:00
  • The most 'strange' part is that `text()` getter works perfectly fine, only the setter... – A. Wolff Dec 05 '15 at 10:04
  • 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: http://jsfiddle.net/uozdnb04/ This is what I mean about it being a long path... – T.J. Crowder Dec 05 '15 at 10:19
  • Ya, i think `text()` accessor should work the same as `html()` (the most relevant comparaison i can think of) – A. Wolff Dec 05 '15 at 10:28
  • 1
    Thanks, this is the relevant answer. I always appreciate to read your posts :) – A. Wolff Dec 06 '15 at 13:54