BAE
BAE

Reputation: 8936

why nodeNames are different?

Jsfiddle here:

<p id="para-01"><span>First span</span></p>
<p id="para-02">
  <span>Second span</span>
</p>

The two paragraphs are nearly the same except the new lines. Why nodeNames are SPAN and #text?

Upvotes: 0

Views: 38

Answers (1)

Ry-
Ry-

Reputation: 224862

Text is a type of node too! Here’s some HTML:

<p>hello <span>world</span></p>

and its corresponding tree:

Element p
    Text "hello "
    Element span
        Text "world"

Whitespace – here, the newline and two spaces – still makes a text node, and your second <p>’s first child is this whitespace-only text node.

You can get the first element child in modern browsers with the firstElementChild property (updated fiddle):

console.log(document.getElementById('para-02').firstElementChild.nodeName)

and in all browsers with the children collection, which only contains elements*:

console.log(document.getElementById('para-02').children[0].nodeName)

* plus comments in IE8 and earlier

Upvotes: 5

Related Questions