This is sort of a very basic question.
If is a <div>
with class="oldClass"
. If I change the class of that div to class="newClass"
using JavaScript(using .className). will all its previous style go away? Or only style which is defined in both classes will be applied after applying newClass
?
to elaborate my question more. if oldClass
is
.oldClass
{
border:1px solid red;
background-color:green;
}
and newClass
is
.newClass{
background-color:black;
}
After applying newClass
using javascript (using .className) which styles will the element have?
(Note- I tested this couple of times using different codes. got different results each time. That's why I am asking even tough its a very basic question)
Only newClass background-color:black;
will be applied
Reply to your Comment: DEMO HERE
Therefore, if you remove "oldClass" by setting the className
to "newClass", the styles defined in your .oldClass
selector will no longer be present on that element, but the .newClass
selector styles will be present.
At any moment, all the style rules that can match an element will be applied to it in a particular order*. If you replace class oldClass with newClass, the element will no longer have the oldClass class, so style rules specified for oldClass may no longer apply to it.
An element can have more than one class at a time. To set more than one class, simply separate them via space.
*) The order is a little more difficult to explain, but the very basics are:
!important
values have the highest priority #element
) .class
and [attr]
) tag
) You can read more about specificity here .
Example:
HTML
<div id="el" class="c1 c2 c3" style="color:green">I am text</div>
CSS:
#el { /* matches elements with id=el */
color:red;
background-color:blue;
}
.c1.c2 { /* matches elements with classes c1 and c2 */
height:50px;
}
.c1,
.c2 { /* matches elements with class c1 and elements with class c2 */
height:100px;
}
.c1 { /* matches elements with class c1 */
color:grey;
background-color:purple;
}
.extra { /* matches elements with class extra */
width:50px;
}
In that example, the div will have the following styles:
If you were to swap c1
for extra
, it will have the following styles:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.