Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need to generate unlimited number of unique id's with jQuery

Tags:

jquery

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>
like image 968
jquery n00b Avatar asked Mar 18 '10 01:03

jquery n00b


2 Answers

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.

like image 161
Daniel A. White Avatar answered Oct 05 '22 20:10

Daniel A. White


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
like image 37
John K Avatar answered Oct 05 '22 19:10

John K