JavaScript Code


How to get items of a list using JavaScript?


Tutorials using JS

Get items of a list

given a list (ordered or unordered), get all the items (li elements) in the list using JavaScript

Solution

since the list items are the children of given list, we can access the list items in the list using Element.children property

list.children

Program

in the following HTML code, we have a list element with four items in it. when user clicks on the button, we get the items in the list using children property. we use a for loop to iterate over the items, and print them to console output

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Get items in list</h2>
<button id="myBtn">Click me</button><br>
<ul id="myList">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>
<pre id="output"></pre>

<script>
document.getElementById("myBtn").addEventListener("click", function() {
    const list = document.getElementById("myList");
    //get items in the list
    const items = list.children;
    //iterate over each of the items using loop
    for ( let i = 0; i < items.length; i++ ) {
        document.getElementById("output").innerHTML += items[i].textContent + "\n";
    }
});
</script>

</body>
</html>

Copyright @2022