I am trying to loop over elements with a specific class and attach an ID to them.
var items = document.getElementsByClassName("item");
for(var i = 0; i < items.length; i++)
{
items[i].id = "item_" + i;
}
console.log(items);
If I run that I get the error Cannot set property 'id' of undefined
However the console.log(items)
returns me the correct collection of items:
HTMLCollection []
0: div.item
1: div.item
length: 2
__proto__: HTMLCollection
But as soon as I try to get the index console.log(testimonials[0])
it is undefined
.
HTML:
<div class="slider">
<div class="item">
Item 1
</div>
</div>
<div class="slider">
<div class="item">
Item 2
</div>
</div>
The issue could be your script is running before the DOM is fully ready.
To solve the issue, you can place your code at the bottom of the body.
OR:
Try wrapping your code with DOMContentLoaded
, this will ensure that your code will be executed once the DOM is fully ready.
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var items = document.getElementsByClassName("item");
for(var i = 0; i < items.length; i++)
{
items[i].id = "item_" + i;
}
console.log(items);
});
</script>
<div class="slider">
<div class="item">
Item 1
</div>
</div>
<div class="slider">
<div class="item">
Item 2
</div>
</div>