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

3

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

The editor I use is the bluefish, which has helped me a lot. I'm learning javascript from w3shcool and I'm currently in the DOM nodes part, and as it's a bit more complicated to understand, I searched for an internet video that would help me understand about us, and found a video explaining the html "family tree" .

When I tested the following code:

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

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

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

How can I resolve this?

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

link

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>
    
asked by anonymous 21.06.2014 / 15:38

1 answer

2

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

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

In your code, it would look like this:

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

link

But nowadays there is a much simpler way of doing this, which does not have 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);
}

link

    
21.06.2014 / 20:45