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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With