简体   繁体   中英

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. 在此处输入图片说明

 $('#div_content img').each(function (index) { $(this).attr("id","id" + index); }); alert($("#div_content").html()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id = 'div_content'> <img src ='img1.png'> <img src ='img2.png'> </div> 

Do not use querySelectorAll since you already use jQuery.

$('#div_content img').each(function (index) {
   $(this).attr("id","id" + index);
});

document.querySelectorAll will return an array of DOMElement s that don't have attr method.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM