For 1: do an if-clause after your first line, e.g. like this:
if(containerClass.length > 1) {
//your addClass code
}
//EDIT: The above would be placed after you define containerClass
in 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-content
having a class or not
For 2:
classes = containerClass.split(' '); //split by space
if(classes[1]) { //if there is a 2nd class
//do something if there are multiple classes
//access the 1st class with classes[0], etc.
} else {
//do something if #main-content only has 1 class
}
//EDIT: in the above, the first line splits whatever the variable containerClass
contains by an empty space. You can compare that with php's explode
function: 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:
classes[0] = 'apples';
classes[1] = 'bananas';
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
if(classes[0]) { ...
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 :)