admin管理员组

文章数量:1302565

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.

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.

Share edited Oct 13, 2014 at 9:24 Rahul Singh 21.8k6 gold badges42 silver badges60 bronze badges asked Oct 13, 2014 at 8:48 Tran Quoc HungTran Quoc Hung 831 silver badge10 bronze badges 3
  • Where l es from? – emerson.marini Commented Oct 13, 2014 at 8:48
  • 1 .querySelectorAll() won't bring you jQuery objects, so you can't use jQuery methods on them. – emerson.marini Commented Oct 13, 2014 at 8:49
  • it loop from 0 to l = items.length. I can set .style.left, .style.top, but can not set attr 'id' – Tran Quoc Hung Commented Oct 13, 2014 at 8:49
Add a ment  | 

2 Answers 2

Reset to default 5

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.

$('#div_content img').each(function (index) {
   $(this).attr("id","id" + index);
});
alert($("#div_content").html());
<script src="https://ajax.googleapis./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 DOMElements that don't have attr method.

本文标签: javascriptSet ID attribute via JqueryStack Overflow