tags:

views:

132

answers:

3

Hi all, 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>
+8  A: 
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.

Daniel A. White
I was beaten to the punch by like 5 seconds!!!
Timothy Khouri
Happens all the time to me as well - I must try be quicker.
Bernhard Hofmann
+2  A: 

Something like this:

var ctr = 1;
$.each( $(".bar"), function( ) {
    $(this).id = "id"+(ctr++);
} );

Using jQuery

  • $(".bar") class selector to grab all the elements with class bar,
  • $.each(selector, func) utility to iterate over the bar elements and address them one by one,
  • $(this) to get a jQuery wrapped element that's current in the iteration,
  • and "id"+(ctr++) simply carries out the logic of assigning id value to attribute, incrementing # each time
John K
A: 
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);
}
M28
Um, the OP wants this in jQuery.
Daniel A. White
sorry, didn't see, shame me :(
M28
@Daniel This will actually work "in jQuery"... ;-)))
deceze
@deceze - true, but its not in jQuery style.
Daniel A. White