Skip to content Skip to sidebar Skip to footer

Javascript Dom - Using Nodelists And Converting To An Array

so I will preface my question with letting you know that this is an assignment for school. I have been working to solve this and I have tried to find the solution within the MDN d

Solution 1:

You can iterate all the <li> items in each <ul> in the page like this while able to separately tell which <ul> they are in:

var list = document.getElementsByTagName("ul");
for (var i = 0; i < list.length; i++) {
    var items = list[i].getElementsByTagName("li");
    for (var j = 0; j < items.length; j++) {
        console.log(items[j]);
    }
}

Or, if you just want all <li> tags, not broken out by <ul>:

var items = document.getElementsByTagName("li");
for (var i = 0; i < items.length; i++) {
    console.log(items[i]);
}

A nodeList or HTMLCollection can be iterated with a simple for loop as seen above. These objects do not have array methods, but can be copied into an array if you really want to use array methods.


Note, it is probably simpler to use document.querySelectorAll() for listing all the <li> elements and you may want to target a specific <ul> tag by putting an id on it in case there are other <ul> and <li> elements in the page.

<ul id="buglist">
    <li>Horse Flies</li><li>Bed bugs</li><li>Mosquito</li><li>Ants</li><li>Mites</li><li>Cricket</li><li>Woolly Bear Caterpillar</li><li>Fleas</li><li>Worms</li><li>Leeches</li>
</ul>

var items = document.querySelectorAll("#buglist li");
for (var j = 0; j < items.length; j++) {
    console.log(items[j]);
}

A nodeList or HTMLCollection can be copied into an array like this:

var list = Array.prototype.slice.call(document.querySelectorAll("#buglist li"), 0);
list.forEach(function(item) {
    console.log(item);
});

Post a Comment for "Javascript Dom - Using Nodelists And Converting To An Array"