You need to create an unlimited number of unique identifiers using jQuery

extreme n00b is here ... I have a number of elements (dynamically generated back end, so there can be a lot of them), and all of them need a unique identifier. I am trying to figure out how to do wth jQuery, and not so well. Any help is appreciated.

In the code below, I would like each "bar" div to get a unique identifier, for example id1, id2, etc. etc.

<div class="foo"> <ul class="bar"> </ul> <ul class="bar"> </ul> <ul class="bar"> </ul> <ul class="bar"> </ul> </div> 
+7
jquery
source share
3 answers
 var id = 1; $('.foo .bar').each( function() { $(this).attr('id', 'id' + id++); }); 

To associate event listeners with them, you need to either do this in a loop or use live .

+10
source share

Something like that:

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

Using jQuery

  • $ (". bar") class selector to capture all elements with the class,
  • $. each (selector, func) utility to iterate over panel elements and access them one by one,
  • $ (this) to get the wrapped jQuery element current in iteration,
  • and "id" + (ctr ++) just follows the logic of assigning an id value to an attribute, increasing the number # each time
+2
source share
 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); } 
0
source share

All Articles