I try to set id for image elements in a div.
<div id = 'div_content'>
<img src ='img1.png'>
<img src ='img2.png'>
</div>
And script:
var items = document.querySelectorAll('#div_content img');
for (var i = 0, l = items.length; i < l; i++) {
items[i].attr("id","id"+i);
};
But it's wrong.

Don't bother using jQuery, just set the property directly. The code's shorter and it's more efficient, too!:
items[i].id = 'id' + i;
NB: items[i] is just a DOM element, you would have had to write $(items[i]) to turn it into a jQuery object with a .attr method.
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