0

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');
Sev
  • 883
  • 1
  • 14
  • 34

5 Answers5

4

Loop!

$('#main-slider div.et_pb_slide').each(function(index) {
    this.id = "slide" + (index + 1);
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Is index coming from the "each" function then? – Sev Aug 04 '14 at 23:11
  • The index comes from the DOM elements (behind the scenes). jQuery uses them to differentiate each from the other. It's a zero based index and is similar to what you'd see with numeric indices in an array. Adding one ensures that you get a "1 based" start point. – scrowler Aug 04 '14 at 23:17
0

You should do something like:

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

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');
scrowler
  • 24,273
  • 9
  • 60
  • 92
  • this is ultimately what I was trying to wright myself. Obviously looping is the better solution but this shows me how I was misusing the .next() function. Thanks. – Sev Aug 04 '14 at 23:14
  • Absolutely - this is just an example for how your attempt should be fixed. Use a loop for sure, otherwise your jQuery code expands with the number of options you have which is no good to anybody. – scrowler Aug 04 '14 at 23:15
0
$( "#main-slider div.et_pb_slide" ).each(function( index ) {
  $(this).attr('id', 'slide' + (index + 1));
});
Ursus
  • 29,643
  • 3
  • 33
  • 50
0

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;
    });
Habib
  • 300
  • 2
  • 14