1

I'm trying to find all text nodes on the page using jquery. But no matter what element I select, the nodeType is always 1:

$.each($('*'), function(index, el) { console.log(el.nodeType) });

Which resulted in nothing but "1" being output in the console. And to prove there is a "text node" on the page:

$('p:first').html()
=> "
            I'm text
          "

$('p:first')[0].nodeType
=> 1

What am I missing here? I'm using safari 5.0.4. I get the same result in firefox 3.6.12.

Thanks.

Binary Logic
  • 2,562
  • 7
  • 31
  • 39

1 Answers1

9

jQuery will only select element nodes.

$('p:first') actually selects the first <p> element. To access the contained text node, you would need to access firstChild at the DOM node:

alert($('p:first')[0].nodeName) // alerts P                 <-- element node
alert($('p:first')[0].firstChild.nodeName) // alerts #text  <-- text node

DEMO

Maybe you also have a misunderstanding: Elements containing text are not text nodes. Every element you create with tags <..> is an element node.

Example:

<p>
  Foo
  <span>Bar</span>
  Baz
</p>

The element node <p> has three children: Two text nodes, containing the text Foo and Baz, and an element node <span> which itself has a text node as child, containing Bar.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • That's true. The whole premise of jQuery is using CSS-like selectors to select elements. – jpsimons Mar 13 '11 at 18:15
  • 1
    @Binary Logic Here is another answer, which describes how to find all text nodes with jQuery: http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery/4399718#4399718 – Nathan Ostgard Mar 13 '11 at 18:17