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
For 1: do an if-clause after your first line, e.g. like this:
//EDIT: The above would be placed after you define
containerClassin your script. It just checks if the container has a class or not, by measuring the content of the variable (.length). If containerClass = “”, this if-condition will be false, and the contained code will not execute. Hence it should prevent your first problem from happening: that the “active” class is added to all its children, regardless of#main-contenthaving a class or notFor 2:
//EDIT: in the above, the first line splits whatever the variable
containerClasscontains by an empty space. You can compare that with php’sexplodefunction: Say your container has 2 classes (class=”aplles bananas”), what you’ll end up with after splitting that by empty space is an array that contains both of these classes like this:So now you have your 1st and 2nd classes, if they exist.
The next line in my code would then do something if #main-content has a 2nd class (here: “bananas”), but you could also check against the first class with
The “else” part in my code would trigger if #main-content doesn’t have a 2nd class. You could expand the above if-else-condition by first checking if a 1st class exists, then checking if a 2nd class exists, and then doing something else (or nothing) if #main-content doesn’t have any classes at all. I hope this makes it clearer.
Hope this helps. On an unrelated note, you might want to add “jquery” to the tags of this post so that more people can find it 🙂