1

I'm creating a set of tabs based upon an existing set of categories with the below JS. I need to extend this to target specific id's within the DIV id based upon values from a JS array.

        $("#categories div[id^=category]:not(:first)", this).hide();

        var cats = $('#categories div[id^=category]');

        cats.each(function () {
           var anch = $(this).find('h3 a').eq(1).clone();
            anch[0].rel = this.id;
            $('<li/>').append(anch).appendTo('#tabs');
        });

The html:

<div id="category_1">
    <h3 class="maintitle">
        <a class="toggle">..</a>
        <a href="#">Cat 1 Title</a>
    </h3>
    <div>
        ...
    </div>
</div>

<div id="category_2">
    <h3 class="maintitle">
        <a class="toggle">..</a>
        <a href="#">Cat 2 Title</a>
    </h3>
    <div>
        ...
    </div>
</div>

I've got a JS array ready by adding:

var catsList = '{$cats}'; // comma separated list of numbers generated in PHP - returns 1,4,8 currently.
var catsArray = catsList.split(',');

How would I convert the below, to check for each item within catsArray ?

var cats = $('#categories div[id^=category]');

Something like

var cats = $('#categories div[id^=category_'+catsArray+']');

but obviously checking each item within the array and not the entire array as that's doing.

tctc91
  • 1,343
  • 2
  • 21
  • 41

2 Answers2

2

you probably want the each function

$.each(catsArray,function(index, item) {
       var cats = $('#categories div[id^=category_'+item+']');
 });

Depending on how you using this a for loop will do it also:

for (var i = 0; i < catsArray.length; i++) {
   var catIndex = catsArray[i];
   var cats = $('#categories div[id^=category_'+catIndex +']');
}
Community
  • 1
  • 1
Liam
  • 27,717
  • 28
  • 128
  • 190
2

You could use that as IDs have to be unique on context page:

var cats = $('#category_'+catsArray.join(',#category_'));

DEMO

A. Wolff
  • 74,033
  • 9
  • 94
  • 155