简体   繁体   中英

Change CSS class by Javascript when default class is set by ID

I have a DIV that has CSS applied to it in an external stylesheet by ID, such as:

<div id="myFavoriteDIVever">Stuff</div>

#myFavoriteDIVever {
    display: none;
}

Then, in a Javascript function, I set the following class to that same DIV:

document.getElementById('myFavoriteDIVever').className = 'superCoolClass';

.superCoolClass {
    display: block;
}

For some reason, when I do it this way, the DIV is not set to display as block. It remains not displayed in the DOM. But if I change it so the DIV has a default CSS class applied to it that sets display: none; then I set a different CSS class to it with Javascript later that sets display: block; it works as expected and displays the DIV as a block element.

Why would the CSS class override the ID CSS? So, when I apply a new className it should override the #element settings. No?

Ids have a higher priority so adding a class will not have any effect. Your best shot is:

<div id="myFavoriteDIVever" class="myFavoriteDIVever">Stuff</div>

.myFavoriteDIVever {
    display: none;
}
document.getElementById('myFavoriteDIVever').className = 'superCoolClass';

Ascending order of specificity

The following list of selectors is by increasing specificity:

  • Universal
  • selectors Type
  • selectors Class
  • selectors Attributes
  • selectors Pseudo-classes
  • ID selectors
  • Inline style

You can overwrite it using inline-styling

 document.getElementById('myFavoriteDIVever').style.display = 'block'; 
 #myFavoriteDIVever { display: none; width: 300px; height: 400px; background: red } 
 <div id="myFavoriteDIVever" class="myFavoriteDIVever">Stuff</div> 

The issue isn't with your javascript, its with the CSS. There is a concept called specificity. The idea is that each CSS entry has some specificity value (1000, 100, 10, 1). The style that will be applied is the one that is the most "specific". An ID selector = 100. A class selector = 10. The id will win. Try changing the css for the class from

.superCoolClass { display: block; }

to

#myFavoriteDIVever.superCoolClass { display: block; }

This should do fine:

HTML:

<div id="myFavoriteDIVever">Stuff</div>

CSS:

#myFavoriteDIVever {
    display: none;
}

#myFavoriteDIVever.show {
    display: block;
}

JS:

document.getElementById('myFavoriteDIVever').className = 'show';

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM