Question : Another DOM question

Hello Experts,

Another simple question,

how can find I how many list items are inside the element id "purchases"? Thanks in advance, I am just trying to undestand a book I bought. I think I need a for loop, but I am not sure how.



<body>

<h1> What to buy</h1>
<p title="a gentle reminder">Dont forget got buy this stuff</p>
<ul id="purchases">
      <li>A tin of beans</li>
      <li>Cheese</li>
      <li>Milk</li>
</ul>

<ul id="animals">
      <li>Pig</li>
      <li>Dog</li>
      <li>Caw</li>
</ul>

<ul id="materials">
      <li>rule</li>
      <li>paper</li>
      <li>pencil</li>
</ul>

<script type="text/javascript">
      var shooping = document.getElementById("purchases");
      var items = document.getElementsByTagName("li");
      
            alert(items.length);
      
</script>

</body>

Answer : Another DOM question

A simple modification of your current code would work. Instead of using document.getElementsByTagName("li"), use shooping.getElementsByTagName("li"). The only time you need a for loop is if you want to loop through the array of returned list items. To find the number of list items, you only need the length property, as you've done.
Random Solutions  
 
programming4us programming4us