Reputation: 2895
When i add .className to change a style of something with or without an event it's not replacing previous styles such as color, it will add new style properties but not replace old ones with new ones.
var loadbutton = document.getElementById('initialbutton');
var loadtext = document.getElementById('altertext');
var mainfunc = function(){
loadtext.className = "changedtext";
}
loadbutton.addEventListener("click",mainfunc,false)
#altertext {
color:#F00;
font-weight:bold;
}
.changedtext {
color:#0F0;
font-style:italic;
font-size:24px;
}
first ID is the original style and the class is the class i want to apply. So onclick it will apply the changed 'font-style' and changed 'font-size' but the color remains red. I want it to replace the red with the new color
Upvotes: 4
Views: 135
Reputation: 17471
Another solution is modify mainfunc
and change the color, but of course @Krasimir answer is the right solution.
var mainfunc = function(){
loadtext.className = "changedtext";
loadtext.style.color = "#0F0";
}
Fiddle: http://jsfiddle.net/qzLa3/1/
Upvotes: 0
Reputation: 5704
With className
you're applying a class to the element, so your CSS declaration for that class should apply.
But you're not removing the rules applied with the ID selector #altertext. These will override any conflicting class rules because the ID is a more specific selector than the class.
If you want to override rules with a class, you should set them using a different class, not an ID.
Upvotes: 2
Reputation: 13529
It's actually a right behaviour. It's all about CSS specificity. The styles in your selector containing id
are with higher specificity then those in the selector containing class
. I'll suggest to put the first styles in a class
, not attaching them to the id
:
.altertext {
color:#F00;
font-weight:bold;
}
Or simply define the things like that
#altertext .changedtext {
color:#0F0;
font-style:italic;
font-size:24px;
}
Using the second approach your specificity is 0110 (#altertext .changedtext), which is higher then 0100 (#altertext).
Upvotes: 4