How do I add a new class to an element dynamically?
Solution 1
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?
Solution 2
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;
}
}
Solution 3
CSS really doesn't have the ability to modify an object in the same manner as JavaScript, so in short - no.
Solution 4
:hover
is a pseudoclass, so you can put your CSS declarations there:
a:hover {
color: #f00;
}
You can also use a list of selectors to apply CSS declarations to a hovered element or an element with a certain class:
.some-class,
a:hover {
color: #f00;
}
Comments
-
itsme over 3 years
Is there any way to add a new CSS class to an element on
:hover
?Like for jQuery, but translated into CSS:
$(element).addClass('someclass');