Skip to content Skip to sidebar Skip to footer

How Can I Assign A Unique Id To All Div's That Have A Specific Class Using Jquery

I am trying to add a unique ID to each div with the class of 'owl-item'. I would like the ID's to go in number order if possible starting with

Solution 1:

Get all the div with class owl-item inside the container with id sample_slider. Use jQuery each to cycle to all these elements and set as attribute the slide- prefix and the current index + 1 if you want to start from 1, remove the +1 if you want to start from 0

$.each($('#sample_slider div.owl-item'), function(ind) {
   $(this).attr('id', 'slide-' + parseInt(ind + 1));
});

Solution 2:

This does what you are asking. It finds all elements with the owl-item class and then adds the appropriate ID to that element. I might suggest using my second example - adding a class rather than ID.

//Iterate through each element with the class of 'owl-item'
$('.owl-item').each(function(eachCounter){

    //Add an ID to each element (slide-#) (eachCounter starts at 0, so add 1)
    $(this).attr("id", "slide-"+parseInt(eachCounter+1));
});

This example adds a class rather than an ID. I think this is a better solution.

//Iterate through each element with the class of 'owl-item'
$('.owl-item').each(function(eachCounter){

   //Add a class to each element (slide-#) (eachCounter starts at 0, so add 1)
   $(this).addClass("slide-"+parseInt(eachCounter+1));
});

Solution 3:

I would do something like this:

$(document).ready(function() {
    $(".owl-item").each(function(i) {
        $(this).attr('id', "owl-item" + (i + 1));
    });
});

Should output unique ID selectors for you to use, such as:

#owl-item1,#owl-item2,#owl-item3 {
   color: $pink; // sample
}

Solution 4:

Your code works, although, you're using a wrong selector (#sample_slider div).

You need to target .owl-item instead.

So, you should do something like this:

$('div.owl-item').each(function(eq, el) {
  el = $(el);
  if (typeof(el.attr('id')) === "undefined") {
    el.prop('id', 'div-' + eq);
    console.log(el.prop('id'));
  }
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="owl-item"></div><divclass="owl-item"></div><divclass="owl-item"></div><divclass="owl-item"></div><divclass="owl-item"></div><divclass="owl-item"></div>

You should also use .prop() instead of .attr().

Post a Comment for "How Can I Assign A Unique Id To All Div's That Have A Specific Class Using Jquery"