changing styles through javascript

why is it better to change/add the styles of an element using javascript by adding/removing a class to it rather than using ".style"
7 Replies
Jochem
Jochem4mo ago
.style sets inline styles, while adding classes adjusts the class attribute with .style, you have to add each and every line separately by adding a class, you can just attach a dozen lines of CSS in one go
bfmv
bfmvOP3mo ago
ohh if my container has "display:flex" on it by default, and im using classlist.add("hide") to change its display from flex to none, but its not happening because maybe two different classes are at conflict how do i fix it btw i just realized that the one that has "display: flex" on it is an ID is that why it is taking a higher precidency
Mannix
Mannix3mo ago
is your hide class higher in the css file then the id that has the display flex on it ? remember about the C in the css
bfmv
bfmvOP3mo ago
i tested all, i placed it above, i placed it below btw its working when i change to ID on the container to a class
Mannix
Mannix3mo ago
so yes it is a specificity issue your id selector has higher specificity i would avoid using id for styling leave it for javascript
bfmv
bfmvOP3mo ago
ohhk and i also had to place the hide class at the bottom should i always place the classes im gonna add through js at the bottom
Jochem
Jochem3mo ago
classes with the same precedence take effect from top to bottom

Did you find this page helpful?