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.

2 Answers 2

2

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

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

DEMO

Sign up to request clarification or add additional context in comments.

Comments

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 +']');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.