How to step through sibling elements

89 Views Asked by At

I am trying to step through 6 Div's and give each a unique ID. I thought for sure that the below code would work but all it does is give the first Div "slide1" and the rest all get "slide6". What is the proper way to do this step through?

    $('#main-slider div.et_pb_slide').first().attr('id','slide1');

    $('#main-slider div.et_pb_slide').next().attr('id','slide2');

    $('#main-slider div.et_pb_slide').next().attr('id','slide3');

    $('#main-slider div.et_pb_slide').next().attr('id','slide4');

    $('#main-slider div.et_pb_slide').next().attr('id','slide5');

    $('#main-slider div.et_pb_slide').next().attr('id','slide6');
5

There are 5 best solutions below

2
tymeJV On BEST ANSWER

Loop!

$('#main-slider div.et_pb_slide').each(function(index) {
    this.id = "slide" + (index + 1);
});
0
Bogdan Martinescu On

You should do something like:

$('#main-slider div.et_pb_slide').each(function(value, index) {
$(this).attr('id','slide'+index);
}); 
2
scrowler On

Failing the other answers here, you should be chaining your jQuery calls together - both for performance reasons and for DOM selector accuracy:

$('#main-slider div.et_pb_slide')
    .first().attr('id','slide1')
    .next().attr('id','slide2')
    .next().attr('id','slide3')
    .next().attr('id','slide4')
    .next().attr('id','slide5')
    .next().attr('id','slide6');
0
Ursus On
$( "#main-slider div.et_pb_slide" ).each(function( index ) {
  $(this).attr('id', 'slide' + (index + 1));
});
0
Habib On

1.) Get all divs using selector

2.) Apply unique id by appending each div index.

    var $divs = $("#main-slider div.et_pb_slide");
    $divs.attr('id', function (index) {
        return 'slide' + index;
    });