Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set ID attribute via Jquery

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. enter image description here

like image 237
Tran Quoc Hung Avatar asked Apr 14 '26 05:04

Tran Quoc Hung


1 Answers

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.

like image 181
Alnitak Avatar answered Apr 16 '26 17:04

Alnitak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!