Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript foreach loop on list items

Tags:

javascript

I have a basic HTML list like below...

<ul class="test_ul">
    <li class="item" id="item1">
        Item 1
    </li>
    <li class="item" id="item2">
        Item 2
    </li>
    <li class="item" id="item3">
        Item 3
    </li>
    <li class="item" id="item4">
        Item 4
    </li>
</ul>

I am using javascript to try and grab the id of each list item and then use a loop to check each one against a string. I have this so far..

var myvariable
myvariable = "item2"
items = document.getElementsByClassName("item");
for (i = 0; i < items.length; i++) {
    console.log(i);
    console.log(item[i]);
}

This isn't working for me, is it because it is not really an array?

like image 753
fightstarr20 Avatar asked Feb 04 '23 08:02

fightstarr20


1 Answers

You're logging the index i, instead, use items[i].id to get the id of the matched element. Something like this

var items = document.getElementsByClassName("item");
for (i = 0; i < items.length; i++) {
  console.log(items[i].id);
}
<ul class="test_ul">
  <li class="item" id="item1">
    Item 1
  </li>
  <li class="item" id="item2">
    Item 2
  </li>
  <li class="item" id="item3">
    Item 3
  </li>
  <li class="item" id="item4">
    Item 4
  </li>
</ul>
like image 128
maazadeeb Avatar answered Feb 16 '23 04:02

maazadeeb