javascript – div.childNodes.item(0) recognizes tab or space as child

Question:

I use Ubuntu 13.10 and know few HTML editors for it.

The editor I use is bluefish, which has helped me a lot. I'm learning javascript through w3shcool and at the moment I'm on the DOM nodes part, and as it's a little more complicated to understand, I looked for a video on the internet that would help me understand about us, and I found a video explaining the "family tree" of the html .

When I tested the following code:

window.onload = function()
{
   var div = document.getElementsByTagName("div").item(0);
   var ul = div.childNodes.item(0);
   Alert(ul);
}

figured it should return as object HTMLULLISTELEMENT ; But it is returned as: object text.

Using firebug I found that the problem is the space between the div and the ul ie the tab that the bluefish editor gives or is it considering the space as text.

How can I solve this?

The well explained video about tree (nodes) is this:

http://www.youtube.com/watch?v=ruV-ZLn6gl8

The full code below:

<html>
<head>
    <title>Core Api</title>
    <script>
        window.onload = function()
        {
            var div = document.getElementsByTagName("div").item(0);
            var ul = div.childNodes.item(0);
            alert(ul);
        }
    </script>
</head>

<body>
    <h2>Árvore</h2>

    <div>
        <ul>
            <li id="item1">
                Primeiro
                <span style="color:blue;">item</span>
                <ul>
                    <li id="item 1.1">item1.1</li>
                    <li id="item 1.2">item1.2</li>
                    <li id="item 1.3">item1.3
                        <ul>
                            <li id="item 1.3.1">item1.3.1
                        </ul>
                    </li>
                </ul>
            </li>
            <li>item2</li>
            <li>item3</li></ul></div>

</body>
</html>

Answer:

DOM nodes can be of various types , including text nodes, which is what you're finding. You can create a function to find the first node of type ELEMENT_NODE . Something like:

function firstElementChild(nodeList) {
    var el = nodeList.firstChild;
    while(el && el.nodeType !== 1) {
        el = el.nextSibling;
    }
    return el;
}

In your code, it would be called like this:

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

http://jsbin.com/minewixo/1/edit

However, nowadays there is a much simpler way to do this, which does not require this function: document.querySelector , which accepts a CSS selector and returns the first element that matches the selector:

window.onload = function()
{
    var ul = document.querySelector('div ul');
    alert(ul);
}

http://jsbin.com/minewixo/2/edit

Scroll to Top
AllEscort