Yahreen
Yahreen

Reputation: 1669

jQuery Shorthand for multiple addClass?

I have this bit of code:

$("body.ow-client1 #stage-nav li.nav1 a").addClass("sub-nav-active");
$("body.ow-client2 #stage-nav li.nav2 a").addClass("sub-nav-active");
$("body.ow-client3 #stage-nav li.nav3 a").addClass("sub-nav-active");
$("body.ow-client4 #stage-nav li.nav4 a").addClass("sub-nav-active");
$("body.ow-client5 #stage-nav li.nav5 a").addClass("sub-nav-active");
$("body.ow-client6 #stage-nav li.nav6 a").addClass("sub-nav-active");
$("body.ow-client7 #stage-nav li.nav7 a").addClass("sub-nav-active");
$("body.ow-client8 #stage-nav li.nav8 a").addClass("sub-nav-active");
$("body.ow-client9 #stage-nav li.nav9 a").addClass("sub-nav-active");

That's all well and good, but I'm wondering if there's a shorthand to write that?

Upvotes: 0

Views: 465

Answers (4)

JaredPar
JaredPar

Reputation: 754585

Try the following

var i;
for (i = 1; i <= 9; i++) {
  var sel = 'body.ow-client' + i + ' #stage-nav li.nav' + i + ' a';
  $(sel).addClass("sub-nav-active");
}

Upvotes: 2

nnnnnn
nnnnnn

Reputation: 150020

You could also do this without JS code, by putting it in the style sheet:

<style>

body.ow-client1 #stage-nav li.nav1 a,
body.ow-client2 #stage-nav li.nav2 a,
body.ow-client3 #stage-nav li.nav3 a,
/* ... */
body.ow-client9 #stage-nav li.nav9 a {
                                       /* styles 
                                          from sub-nav-active
                                          here */
                                     }
</style>

You wouldn't actually have a class called sub-nav-active anymore, you'd just apply the appropriate styles using the selectors as shown above.

(Obviously this solution only works if the only point of having sub-nav-active is to apply styles to the anchor elements within the active section: if you are also using it in other JS code as a jQuery selector then it wouldn't work.)

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230306

For one thing, you could just concat selectors together:

$("body.ow-client1 #stage-nav li.nav1 a, body.ow-client2 #stage-nav li.nav2 a, body.ow-client3 #stage-nav li.nav3 a").addClass("sub-nav-active");

But this is harder to read. Why do you need to have numbered ow-clientX classes?

Upvotes: 2

Tyler Crompton
Tyler Crompton

Reputation: 12652

I think this is the only way you can do that.

$("body.ow-client9 #stage-nav li a").addClass("sub-nav-active");

Upvotes: 0

Related Questions