Reputation: 105
extreme n00b here... I've got a number of elements (dynamically generated by back end so it could be quite a few) and all need a unique id. I'm trying to work out how to do this wth jQuery and not doing so well. Any help is appreciated.
In the code below, I'd want each "bar" div to get a unique id, like id1, id2 etc etc
<div class="foo">
<ul class="bar">
</ul>
<ul class="bar">
</ul>
<ul class="bar">
</ul>
<ul class="bar">
</ul>
</div>
Upvotes: 7
Views: 2074
Reputation:
function makeAllTheThingsThatTheOPRequested(num){
var ms = document.createElement('div');
ms.setattribute("class","your_class_name");
var uls=[];
for(var i=0;i<num;i++){
var tmp = document.createElement('ul');
tmp.setattribute("class","your_class_name");
ms.addChild(tmp)
uls.push(tmp);
}
document.body.addChild(ms);
}
Upvotes: 0
Reputation: 190907
var id = 1;
$('.foo .bar').each(
function() {
$(this).attr('id', 'id' + id++);
});
In order to bind event listeners to these, you have to either do it in the loop or use live
.
Upvotes: 10
Reputation: 28869
Something like this:
var ctr = 1;
$.each( $(".bar"), function( ) {
$(this).id = "id"+(ctr++);
} );
Using jQuery
Upvotes: 2