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?
9 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>
-
6Instead of
document.getElementById('mydiv').className += ' newClass';
, useclassList
to add and remove classes:document.getElementById('mydiv').classList.add('newclass');
. By doing it this way, you won't need to test if the class already exists before adding it, the add method will do that for you. Likewise with remove, you won't have to test if a class exists before manipulating theclassName
property. You also don't have to remember to prefix the class you're adding with a space.– nwayveJul 4, 2014 at 0:54 -
1@nwayve:
classList
is only supported on IE >= 10, Chrome >= 34, Firfox >= 29 and Safari >= 7. Source: caniuse.com/#search=classList . If you need support for older browsers, useclassName
.– AsaphJul 5, 2014 at 7:25 -
3@Asaph: Actually it's supported in Chrome >= 8.0, Firefox >= 3.6, Safari >=5.1, Opera >= 11.5, and IE >= 10.0. Source(click on Show all versions). The only older browser you should worry about support for is IE <= 9.0 which a polyfill like classList.js should work fine for.– nwayveJul 5, 2014 at 16:04
-
@nwayve: The source you linked is the same one I did. But I wasn't aware that I need to click on "Show all versions" to see the minimum supported version (not the most intuitive ui if you ask me). Thanks for the clarification. In any case, the point still stands,
className
is more backwards compatible thanclassList
.– AsaphJul 6, 2014 at 5:21 -
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.
-
2to clarify - jQuery hasn't dropped support for IE<9. They still update the 1.x branch, which is designed to have IE browser support. 2.x has no such support, but is somewhat faster because of this.– SteveBJan 3, 2014 at 11:00
-
I think this is the best pure JS solution, using
add
andremove
. Much better than the accepted answer.– mbomb007Nov 25, 2015 at 21:34
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.
-
thanks for the tips sir. I'll get into that soon. I am just starting to read about javascript ;)– sasoriFeb 8, 2010 at 12:03
-
Another benefit in using a framework is that you can more easily add or remove class names rather than simply replace the entire class attribute's value (e.g. to remove "myclass" from an element with a class attribute of "myclass myotherclass" you'd otherwise have to replace the attribute value with "myotherclass" or do something funky like split the string into an array and remove the entry "myclass" from it before joining it back together, etc. Go Frameworks! Feb 8, 2010 at 12:18
-
I never entertained the idea of using a Javascript library as I thought it'd just be yet another framework to use, another JS file to download, another place to debug to find problems... yada yada yada. One day I was bored, bit the bullet and tried jQuery. Within an hour I'd vowed never to create a website or webapp without it - it's so easy! You could probably even learn jQuery and never touch any other Javascript. Feb 8, 2010 at 15:32
-
1It's good to know how to do things without a framework, for understanding and when you want to make something truly lightweight, but there's no reason to not use a library like jQuery for most development. Feb 8, 2010 at 20:41
-
1Totally agree, Mark. I now think of it like being a manager - never delegate work to a sub-ordinate that you wouldn't be able to do yourself. I.e. never use a framework to do something you wouldn't know how to do yourself. Feb 9, 2010 at 21:00
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.
use the className
property:
document.getElementById('your_element_s_id').className = 'cssClass';
-
3Be carefull, if you just want to add a new class, this way will replace all the class="" attributes, not just append the new one. Feb 8, 2010 at 11:22
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.
You may also be interested in modifying it using jQuery: http://api.jquery.com/category/css/
<!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>