.firstChild returning the wrong child

4

The error is very simple but can not find.

I'm learning how to use the DOM CORE API. I created a DIV, and inside I put a UL. I am alerting who is the first child of the DIV, and the result is giving OBJECT TEXT . instead of giving OBJECT UL LIST . follow 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>

javaScript code

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

    
asked by anonymous 03.11.2016 / 16:46

1 answer

4

What you are 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.

Notice 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 it gives #text , but in the second not 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
    
03.11.2016 / 16:50