简体   繁体   中英

Detecting attributes of elements in the HTML DOM with javascript

So much confusion, so few answers. I'm trying to loop through the DOM, looking for a specific node by id, however, this code has several problems for which I have no explanation. First, the length of the childNodes list comes up as '5'. Two "ul"'s, two "id"'s, if those count...and one for luck?

Second, it dies at if(y[i].hasAttribute('id')===true) . Firebug says this is not a function. I have no reason to not believe it, but am not sure why it isn't.

Thank you for any help.

<div id="list">
<ul id="first"></ul>
<ul  id="second"></ul>
</div>
    <script>
        var comments=document.getElementById('list')
                        var y=comments.childNodes;
                        var count=y.length
                        for(i=0;i<count;i++)
                        {
                            document.write(y.length);
                            if(y[i].hasAttribute('id')===true)
                            { document.write('here!');}

                        }
    </script>

the childNodes attribute contains all nodes in the DOM, which specifically means, it includes text nodes. you have 3 of them - the newline/linefeed characters inside your div.

you can test for element children using the nodeType attribute ( see eg. here ; 1 represents ELEMENT_NODE , 3 stands for TEXT_NODE ).

If you use a tool like Firebug and inspect the DOM itself, you would see all the children of an element and the difference between .children and .childNodes .

It's by hunting around in the DOM that I discovered why there are so many things that at first appear to be duplicates of each other, but are definitely not. The Mozilla developers site developer.mozilla.org is also a wealth of information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM