[Solved] jQuery toggle() with dynamic div ID’s


This is the best way I could come up with:

var divs = $('div[id^="category-"]');
var num = divs.length;

for (i=1; i<=num; i++) {
    $('<button class="toggles" />')
        .text('Toggle div ' + i)
        .appendTo('#divToAddButtonsTo');
}

$('.toggles').live('click',
                   function(){
                       var thisIs = $(this).index();
                       $('div[id^="category-"]').eq(thisIs).toggle();
                   });

JS Fiddle demo.

Obviously this is run inside the $(document).ready().

References:

7

solved jQuery toggle() with dynamic div ID’s