Search code examples
javascriptjquerycssiterationstep-through

How to step through sibling elements


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');

Solution

  • Loop!

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