How do I add a new class to an element dynamically?
Short answer no :)
But you could just use the same CSS for the hover like so:
a:hover, .hoverclass {
background:red;
}
Maybe if you explain why you need the class added, there may be a better solution?
CSS really doesn't have the ability to modify an object in the same manner as JavaScript, so in short - no.
Since everyone has given you jQuery/JS answers to this, I will provide an additional solution. The answer to your question is still no, but using LESS (a CSS Pre-processor) you can do this easily.
.first-class {
background-color: yellow;
}
.second-class:hover {
.first-class;
}
Quite simply, any time you hover over .second-class
it will give it all the properties of .first-class
. Note that it won't add the class permanently, just on hover. You can learn more about LESS here: Getting Started with LESS
Here is a SASS way to do it as well:
.first-class {
background-color: yellow;
}
.second-class {
&:hover {
@extend .first-class;
}
}