Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a css class style through Javascript?

According to the book I am reading it is better to change CSS by class when you are using Javascript. But how? Can someone give a sample snippet for this?

like image 871
sasori Avatar asked Feb 08 '10 11:02

sasori


People also ask

Can I change CSS class in JavaScript?

JavaScript offers us two properties that we can use to modify CSS classes; classList and className property. The className property is used to set a value to a CSS class directly whereas the classList gives us some built-in methods to manipulate the CSS classes.

Can JavaScript manipulate CSS?

Now, JavaScript is a powerful language, so not only can we manipulate HTML elements with it, but we can also use it to manipulate the CSS properties of any webpage. In this tutorial, I will teach you how to manipulate the styling of a webpage by building a simple project.

How do I modify a CSS class?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)


2 Answers

Suppose you have:

<div id="mydiv" class="oldclass">text</div> 

and the following styles:

.oldclass { color: blue } .newclass { background-color: yellow } 

You can change the class on mydiv in javascript like this:

document.getElementById('mydiv').className = 'newclass'; 

After the DOM manipulation you will be left with:

<div id="mydiv" class="newclass">text</div> 

If you want to add a new css class without removing the old one, you can append to it:

document.getElementById('mydiv').className += ' newClass'; 

This will result in:

<div id="mydiv" class="oldclass newclass">text</div> 
like image 57
Asaph Avatar answered Oct 09 '22 12:10

Asaph


Since classList is supported in all major browsers and jQuery drops support for IE<9 (in 2.x branch as Stormblack points in the comment), considering this HTML

<div id="mydiv" class="oldclass">text</div> 

you can comfortably use this syntax:

document.getElementById('mydiv').classList.add("newClass"); 

This will also result in:

<div id="mydiv" class="oldclass newclass">text</div> 

plus you can also use remove, toggle, contains methods.

like image 28
Jan Turoň Avatar answered Oct 09 '22 11:10

Jan Turoň