store in a variable only the first or only the second class of an element
Posted
by shecky
on Stack Overflow
See other posts from Stack Overflow
or by shecky
Published on 2010-04-22T17:10:56Z
Indexed on
2010/04/22
17:13 UTC
Read the original article
Hit count: 189
I'm using this bit of jQ to add a class to two different elements based on the class of another (parent/grandparent, etc) element:
$(document).ready(function(){
var containerClass = $('#main-content').attr('class');
$('#nav-primary li#'+containerClass).addClass('active');
$('#aux-left div[id$='+containerClass+']').addClass('active');
});
Brilliant, but I have two problems with it:
First, when there's no class at all in <div id="main-content">
, the 'active' class is added to all the #nav-primary LIs, and also to all the #aux-left DIVs; how can I modify this so that in the absence of any class on #main-content, do nothing?
Second, how can I target only the first or second of multiple classes to store in the 'containerClass' variable, e.g., <div id="main-content" class="apples bananas">
?
Very much appreciated! svs
© Stack Overflow or respective owner