gxvigo
gxvigo

Reputation: 837

Traversing DOM in Javascript (nodeType)

I started exploring how to manipulate DOM with Javascript. I started from the very basic but I got immediately stuck.

So from W3 I found that there are 3 types of nodes in HTML:

  1. element
  2. attribute
  3. text

Taking this snippet as example <p id="myId">My paragraph</p> I would say:

  1. <p>
  2. id
  3. My paragraph

But when I apply this concept in code, it doesn't work. Here my example:

<! DOCTYPE html>
<html>
<head></head>
<body>    
    <script>

        var htmlElement = document.documentElement;
        var headElement = htmlElement.firstChild
        var bodyElement = headElement.nextSibling;

        alert (bodyElement.nodeType);

    </script>
</body>

As you can imagine from my variable name, I would expect to have "1" as result of my alert (it would be the element 'body'), instead I receive a "3" which is a text. But I don't have any text in my "head" element.

How can I explain this?

Upvotes: 0

Views: 112

Answers (1)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85643

JavaScript cares for the new line (\n) too so when you use nextSibling it get also get new line character.

So, using the following code:

headElement.nextSibling

will results \n now to get body element you need to use nextSibling again:

headElement.nextSibling.nextSibling

Alternatively, you may use nextElementSibling by which you just get next sibling of type element:

headElement.nextElementSibling

Upvotes: 2

Related Questions