1

I am trying to simplify a list of functions down to a single function. Basically I have 6 divs, each with the id #slide_ where the underscore is a number from 1-6 (#slide1, #slide2, etc).

My functions are something like this:

if ($("#slide1").hasClass('active')) {});

There is one of these if statements for each of the #slide_ ids. What is the best way to simplify this so I have have a single function instead of 6 different if statements?

1
  • Your code in fiddle has several mistakes. Take a look at updated fiddle Commented Aug 22, 2014 at 22:32

2 Answers 2

3

Loop that sucker up! First, apply a class (I use .slide for example purposes):

var $slides = $('.slide');

Or (if you can't mod the HTML) you can use the "starts with" selector that @j08691 references:

var $slides = $('[id^="slide"]');

Then apply a for loop on that collection:

for(var i = $slides.length; i--;){
    if($slides.eq(i).hasClass('active')){
        // do your magic
    }
}

Or you can take it even farther and if you are doing something to the same object, just filter the record set:

$slides.filter(function(){
    return $(this).hasClass('active');
}).applyMethod();

If you are modifying objects other than the slides then use the loop, else if you are modifying the slides themselves use the filter. Either way, it should work.

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

Comments

3

Use the starts with selector:

$("[id^='slide']").each(...)

Note though that this will match all elements with an ID that begins with "slide". The better solution is to assign a class to the elements you want to target, and select the class instead.

19 Comments

What is the point if jQuery is only going to test the first element every time? This isn't going to work.
Your code is the same as $("#slide1").hasClass("active");.
@Derek朕會功夫 - No, my code would match $("#slide2"), $("#slide3"), etc as well. Yours wouldn't.
Oh I see where we're not on the same page. Yes of course, however I'm assuming that he's looping already. Sorry for the confusion.
@Derek朕會功夫 yes, the answer has to be $("[id^='slide'].active").each(function() {});
|

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.