How to change a css class style through Javascript?

JavascriptHtmlCss

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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>

Solution 2 - Javascript

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.

Solution 3 - Javascript

I'd highly recommend jQuery. It then becomes as simple as:

$('#mydiv').addClass('newclass');

You don't have to worry about removing the old class then as addClass() will only append to it. You also have removeClass();

The other advantage over the getElementById() method is you can apply it to multiple elements at the same time with a single line of code.

$('div').addClass('newclass');
$('.oldclass').addClass('newclass');

The first example will add the class to all DIV elements on the page. The second example will add the new class to all elements that currently have the old class.

Solution 4 - Javascript

If you want to manipulate the actual CSS class instead of modifying the DOM elements or using modifier CSS classes, see https://stackoverflow.com/a/50036923/482916.

Solution 5 - Javascript

use the className property:

document.getElementById('your_element_s_id').className = 'cssClass';

Solution 6 - Javascript

There are two ways in which this can be accomplished using vanilla javascript. The first is className and the second is classList. className works in all browsers but can be unwieldy to work with when modifying an element's class attribute. classList is an easier way to modify an element's class(es).

To outright set an element's class attribute, className is the way to go, otherwise to modify an element's class(es), it's easier to use classList.

Initial Html

<div id="ID"></div>

Setting the class attribute

var div = document.getElementById('ID');
div.className = "foo bar car";

Result:

<div id="ID" class="foo bar car"></div>

Adding a class

div.classList.add("car");// Class already exists, nothing happens
div.classList.add("tar");

Note: There's no need to test if a class exists before adding it. If a class needs to be added, just add it. If it already exists, a duplicate won't be added.
Result:

<div id="ID" class="foo bar car tar"></div>

Removing a class

div.classList.remove("car");
div.classList.remove("tar");
div.classList.remove("car");// No class of this name exists, nothing happens

Note: Just like add, if a class needs to be removed, remove it. If it's there, it'll be removed, otherwise nothing will happen.
Result:

<div id="ID" class="foo bar"></div>

Checking if a class attribute contains a specific class

if (div.classList.contains("foo")) {
  // Do stuff
}

Toggling a class

var classWasAdded = div.classList.toggle("bar"); // "bar" gets removed
// classWasAdded is false since "bar" was removed

classWasAdded = div.classList.toggle("bar"); // "bar" gets added
// classWasAdded is true since "bar" was added

.toggle has a second boolean parameter that, in my opinion, is redundant and isn't worth going over.

For more information on classList, check out MDN. It also covers browser compatibility if that's a concern, which can be addressed by using Modernizr for detection and a polyfill if needed.

Solution 7 - Javascript

document.getElementById("my").className = 'myclass';

Solution 8 - Javascript

You may also be interested in modifying it using jQuery: http://api.jquery.com/category/css/

Solution 9 - Javascript

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
        $("div").addClass(function(){
            return "par" ;
    });
});
</script>
<style>
.par {
    color: blue;
}
</style>
</head>
<body>
<div class="test">This is a paragraph.</div>
</body>
</html>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsasoriView Question on Stackoverflow
Solution 1 - JavascriptAsaphView Answer on Stackoverflow
Solution 2 - JavascriptJan TuroňView Answer on Stackoverflow
Solution 3 - JavascriptAndy ShellamView Answer on Stackoverflow
Solution 4 - Javascriptgmoz22View Answer on Stackoverflow
Solution 5 - JavascriptknittlView Answer on Stackoverflow
Solution 6 - JavascriptnwayveView Answer on Stackoverflow
Solution 7 - JavascriptAdirView Answer on Stackoverflow
Solution 8 - JavascriptJuriView Answer on Stackoverflow
Solution 9 - Javascriptchanakya sView Answer on Stackoverflow