.firstchild returning the wrong son

Asked

Viewed 54 times

3

Error is very simple but can not find.

I am learning to use the DOM CORE API.
I created a DIV, and inside I put an UL.
I’m warning you who the DIV’s first child is, and the results are coming in OBJECT TEXT. instead of giving OBJECT UL LIST. follows the code.

<html lang="pt-BR">
    <head>
        <title>Dom Core Api</title>
        <meta charset="utf-8">
        <script src="js/testDom.js"></script>
    </head>
    <body>
      <div>
          <ul><li>Rodrigo</li>
            <li>Robson</li>
          </ul>
      </div>
    </body>
</html>

Code Avascript

window.onload = function() {
    var div = document.getElementsByTagName("div").item(0);
    alert(div.firstChild);
}

Resultado no Navegador

  • the post was adjusted

  • Improved quite adjusted.

1 answer

4


What you’re looking for is .firstElementChild that gives you the first child that is an element. When you use only .firstChild it will give you the blank text and the line break you have in HTML.

Look at this example:

var div1 = document.getElementsByTagName('div').item(0);
console.log(div1.firstChild, div1.firstElementChild); // #text, ul

var div2 = document.getElementsByTagName('div').item(1);
console.log(div2.firstChild, div2.firstElementChild); // ul, ul
<div>
    <ul>
        <li>A</li>
        <li>B</li>
    </ul>
</div>
<div><ul><li>A</li><li>B</li></ul></div>

In the first example gives #text, but not the second because there is no space between the HTML of div and ul.

You can also test the .nodeType that will confirm the differences:

console.log(div1.firstChild.nodeType, div1.firstElementChild.nodeType); // 3, 1
console.log(div2.firstChild.nodeType, div2.firstElementChild.nodeType); // 1, 1
  • 1

    It’s true now it worked, I was studying through the XTI channel, and there he did . firstchild and returned the element normally, even with space. But thanks, solved the problem.

  • 1

    @Rodrigojacinto if the answer answered you, you can then mark it as accepted.

  • 1

    Just to warn, even IE8 still needs to use the old method, checking the type of each Node to see if it is element or not.

  • 1

    @bfavaretto well seen. I’ve left the IE8 behind, but there may still be those who use.

  • 1

    I’ve abandoned it too. It was almost as good as the day I said goodbye to IE6 :)

  • @bfavaretto haha :)

  • But the browser I use is Google Chrome, not IE8

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.