jquery n00b
jquery n00b

Reputation: 105

need to generate unlimited number of unique id's with 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>

Upvotes: 7

Views: 2074

Answers (3)

user216441
user216441

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

Daniel A. White
Daniel A. White

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

John K
John K

Reputation: 28869

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

Upvotes: 2

Related Questions