How can I change the class of an HTML element in response to an onclick
or any other events using JavaScript?
This question is related to
javascript
html
dom
This is working for me:
function setCSS(eleID) {
var currTabElem = document.getElementById(eleID);
currTabElem.setAttribute("class", "some_class_name");
currTabElem.setAttribute("className", "some_class_name");
}
This is easiest with a library like jQuery:
<input type="button" onClick="javascript:test_byid();" value="id='second'" />
<script>
function test_byid()
{
$("#second").toggleClass("highlight");
}
</script>
Lots of answers, lots of good answers.
TL;DR :
document.getElementById('id').className = 'class'
OR
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');
That's it.
And, if you really want to know the why and educate yourself then I suggest reading Peter Boughton's answer, it's perfect.
Note:
This is possible with (document or event):
getElementById()
getElementsByClassName()
querySelector()
querySelectorAll()
A couple of minor notes and tweaks on the previous regexes:
You'll want to do it globally in case the class list has the class name more than once. And, you'll probably want to strip spaces from the ends of the class list and convert multiple spaces to one space to keep from getting runs of spaces. None of these things should be a problem if the only code dinking with the class names uses the regex below and removes a name before adding it. But. Well, who knows who might be dinking with the class name list.
This regex is case insensitive so that bugs in class names may show up before the code is used on a browser that doesn't care about case in class names.
var s = "testing one four one two";
var cls = "one";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "test";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "testing";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "tWo";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
The OP question was How can I change an element's class with JavaScript?
Modern browsers allow you to do this with one line of javascript:
document.getElementById('id').classList.replace('span1','span2')
The classList
attribute provides a DOMTokenList which has a variety of methods. You can operate on an element's classList using simple manipulations like add(), remove() or replace(). Or get very sophisticated and manipulate classes like you would an object or Map with keys(), values(), entries()
Peter Boughton's answer is a great one but it's now over a decade old. All modern browsers now support DOMTokenList - see https://caniuse.com/#search=classList and even IE11 supports some DOMTokenList methods
In one of my old projects that did not use jQuery, I built the following functions for adding, removing and checking if element has class:
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
if (!hasClass(ele, cls)) ele.className += " " + cls;
}
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ');
}
}
So, for example, if I want onclick
to add some class to the button I can use this:
<script type="text/javascript">
function changeClass(btn, cls) {
if(!hasClass(btn, cls)) {
addClass(btn, cls);
}
}
</script>
...
<button onclick="changeClass(this, "someClass")">My Button</button>
By now for sure it would just be better to use jQuery.
You may try to use node attributes
property to keep compatibility with old browsers even IE6:
function getClassNode(element) {_x000D_
for (var i = element.attributes.length; i--;)_x000D_
if (element.attributes[i].nodeName === 'class')_x000D_
return element.attributes[i];_x000D_
}_x000D_
_x000D_
function removeClass(classNode, className) {_x000D_
var index, classList = classNode.value.split(' ');_x000D_
if ((index = classList.indexOf(className)) > -1) {_x000D_
classList.splice(index, 1);_x000D_
classNode.value = classList.join(' ');_x000D_
}_x000D_
}_x000D_
_x000D_
function hasClass(classNode, className) {_x000D_
return classNode.value.indexOf(className) > -1;_x000D_
}_x000D_
_x000D_
function addClass(classNode, className) {_x000D_
if (!hasClass(classNode, className))_x000D_
classNode.value += ' ' + className;_x000D_
}_x000D_
_x000D_
document.getElementById('message').addEventListener('click', function() {_x000D_
var classNode = getClassNode(this);_x000D_
var className = hasClass(classNode, 'red') && 'blue' || 'red';_x000D_
_x000D_
removeClass(classNode, 'red');_x000D_
removeClass(classNode, 'blue');_x000D_
_x000D_
addClass(classNode, className);_x000D_
})
_x000D_
.red {_x000D_
color: red;_x000D_
}_x000D_
.red:before {_x000D_
content: 'I am red! ';_x000D_
}_x000D_
.red:after {_x000D_
content: ' again';_x000D_
}_x000D_
.blue {_x000D_
color: blue;_x000D_
}_x000D_
.blue:before {_x000D_
content: 'I am blue! '_x000D_
}
_x000D_
<span id="message" class="">Click me</span>
_x000D_
The line
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/\bMyClass\b/','')
should be:
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace('/\bMyClass\b/','');
This is easiest with a library like jQuery:
<input type="button" onClick="javascript:test_byid();" value="id='second'" />
<script>
function test_byid()
{
$("#second").toggleClass("highlight");
}
</script>
try
element.className='second'
function change(box) { box.className='second' }
_x000D_
.first { width: 70px; height: 70px; background: #ff0 }_x000D_
.second { width: 150px; height: 150px; background: #f00; transition: 1s }
_x000D_
<div onclick="change(this)" class="first">Click me</div>
_x000D_
Working JavaScript code:
<div id="div_add" class="div_add">Add class from Javascript</div>
<div id="div_replace" class="div_replace">Replace class from Javascript</div>
<div id="div_remove" class="div_remove">Remove class from Javascript</div>
<button onClick="div_add_class();">Add class from Javascript</button>
<button onClick="div_replace_class();">Replace class from Javascript</button>
<button onClick="div_remove_class();">Remove class from Javascript</button>
<script type="text/javascript">
function div_add_class()
{
document.getElementById("div_add").className += " div_added";
}
function div_replace_class()
{
document.getElementById("div_replace").className = "div_replaced";
}
function div_remove_class()
{
document.getElementById("div_remove").className = "";
}
</script>
You can download a working code from this link.
Here's a toggleClass to toggle/add/remove a class on an element:
// If newState is provided add/remove theClass accordingly, otherwise toggle theClass
function toggleClass(elem, theClass, newState) {
var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');
var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));
elem.className=elem.className.replace(matchRegExp, ''); // clear all
if (add) elem.className += ' ' + theClass;
}
see jsfiddle
also see my answer here for creating a new class dynamically
I would use jQuery and write something like this:
jQuery(function($) {
$("#some-element").click(function() {
$(this).toggleClass("clicked");
});
});
This code adds a function to be called when an element of the id some-element is clicked. The function appends clicked to the element's class attribute if it's not already part of it, and removes it if it's there.
Yes you do need to add a reference to the jQuery library in your page to use this code, but at least you can feel confident the most functions in the library would work on pretty much all the modern browsers, and it will save you time implementing your own code to do the same.
Thanks
A couple of minor notes and tweaks on the previous regexes:
You'll want to do it globally in case the class list has the class name more than once. And, you'll probably want to strip spaces from the ends of the class list and convert multiple spaces to one space to keep from getting runs of spaces. None of these things should be a problem if the only code dinking with the class names uses the regex below and removes a name before adding it. But. Well, who knows who might be dinking with the class name list.
This regex is case insensitive so that bugs in class names may show up before the code is used on a browser that doesn't care about case in class names.
var s = "testing one four one two";
var cls = "one";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "test";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "testing";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
var cls = "tWo";
var rg = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", 'ig');
alert("[" + s.replace(rg, ' ') + "]");
The line
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/\bMyClass\b/','')
should be:
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace('/\bMyClass\b/','');
Just thought I'd throw this in:
function inArray(val, ary){
for(var i=0,l=ary.length; i<l; i++){
if(ary[i] === val){
return true;
}
}
return false;
}
function removeClassName(classNameS, fromElement){
var x = classNameS.split(/\s/), s = fromElement.className.split(/\s/), r = [];
for(var i=0,l=s.length; i<l; i++){
if(!iA(s[i], x))r.push(s[i]);
}
fromElement.className = r.join(' ');
}
function addClassName(classNameS, toElement){
var s = toElement.className.split(/\s/);
s.push(c); toElement.className = s.join(' ');
}
You can use node.className
like so:
document.getElementById('foo').className = 'bar';
This should work in IE5.5 and up according to PPK.
As well you could extend HTMLElement object, in order to add methods to add, remove, toggle and check classes (gist):
HTMLElement = typeof(HTMLElement) != 'undefiend' ? HTMLElement : Element;
HTMLElement.prototype.addClass = function(string) {
if (!(string instanceof Array)) {
string = string.split(' ');
}
for(var i = 0, len = string.length; i < len; ++i) {
if (string[i] && !new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)').test(this.className)) {
this.className = this.className.trim() + ' ' + string[i];
}
}
}
HTMLElement.prototype.removeClass = function(string) {
if (!(string instanceof Array)) {
string = string.split(' ');
}
for(var i = 0, len = string.length; i < len; ++i) {
this.className = this.className.replace(new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)'), ' ').trim();
}
}
HTMLElement.prototype.toggleClass = function(string) {
if (string) {
if (new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className)) {
this.className = this.className.replace(new RegExp('(\\s+|^)' + string + '(\\s+|$)'), ' ').trim();
} else {
this.className = this.className.trim() + ' ' + string;
}
}
}
HTMLElement.prototype.hasClass = function(string) {
return string && new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className);
}
And then just use like this (on click will add or remove class):
document.getElementById('yourElementId').onclick = function() {
this.toggleClass('active');
}
Here is demo.
just say myElement.classList="new-class"
unless you need to maintain other existing classes in which case you can use the classList.add, .remove
methods.
var doc = document;_x000D_
var divOne = doc.getElementById("one");_x000D_
var goButton = doc.getElementById("go");_x000D_
_x000D_
goButton.addEventListener("click", function() {_x000D_
divOne.classList="blue";_x000D_
});
_x000D_
div{_x000D_
min-height:48px;_x000D_
min-width:48px;_x000D_
}_x000D_
.bordered{_x000D_
border: 1px solid black;_x000D_
}_x000D_
.green{_x000D_
background:green;_x000D_
}_x000D_
.blue{_x000D_
background: blue;_x000D_
}
_x000D_
<button id="go">Change Class</button>_x000D_
_x000D_
<div id="one" class="bordered green">_x000D_
_x000D_
</div>
_x000D_
As well you could extend HTMLElement object, in order to add methods to add, remove, toggle and check classes (gist):
HTMLElement = typeof(HTMLElement) != 'undefiend' ? HTMLElement : Element;
HTMLElement.prototype.addClass = function(string) {
if (!(string instanceof Array)) {
string = string.split(' ');
}
for(var i = 0, len = string.length; i < len; ++i) {
if (string[i] && !new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)').test(this.className)) {
this.className = this.className.trim() + ' ' + string[i];
}
}
}
HTMLElement.prototype.removeClass = function(string) {
if (!(string instanceof Array)) {
string = string.split(' ');
}
for(var i = 0, len = string.length; i < len; ++i) {
this.className = this.className.replace(new RegExp('(\\s+|^)' + string[i] + '(\\s+|$)'), ' ').trim();
}
}
HTMLElement.prototype.toggleClass = function(string) {
if (string) {
if (new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className)) {
this.className = this.className.replace(new RegExp('(\\s+|^)' + string + '(\\s+|$)'), ' ').trim();
} else {
this.className = this.className.trim() + ' ' + string;
}
}
}
HTMLElement.prototype.hasClass = function(string) {
return string && new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className);
}
And then just use like this (on click will add or remove class):
document.getElementById('yourElementId').onclick = function() {
this.toggleClass('active');
}
Here is demo.
No offense, but it's unclever to change class on-the-fly as it forces the CSS interpreter to recalculate the visual presentation of the entire web page.
The reason is that it is nearly impossible for the CSS interpreter to know if any inheritance or cascading could be changed, so the short answer is:
Never ever change className on-the-fly !-)
But usually you'll only need to change a property or two, and that is easily implemented:
function highlight(elm){
elm.style.backgroundColor ="#345";
elm.style.color = "#fff";
}
You can use node.className
like so:
document.getElementById('foo').className = 'bar';
This should work in IE5.5 and up according to PPK.
Using pure JavaScript code:
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
if (!this.hasClass(ele, cls)) ele.className += " " + cls;
}
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ');
}
}
function replaceClass(ele, oldClass, newClass){
if(hasClass(ele, oldClass)){
removeClass(ele, oldClass);
addClass(ele, newClass);
}
return;
}
function toggleClass(ele, cls1, cls2){
if(hasClass(ele, cls1)){
replaceClass(ele, cls1, cls2);
}else if(hasClass(ele, cls2)){
replaceClass(ele, cls2, cls1);
}else{
addClass(ele, cls1);
}
}
Just to add on information from another popular framework, Google Closures, see their dom/classes class:
goog.dom.classes.add(element, var_args)
goog.dom.classes.addRemove(element, classesToRemove, classesToAdd)
goog.dom.classes.remove(element, var_args)
One option for selecting the element is using goog.dom.query with a CSS3 selector:
var myElement = goog.dom.query("#MyElement")[0];
The OP question was How can I change an element's class with JavaScript?
Modern browsers allow you to do this with one line of javascript:
document.getElementById('id').classList.replace('span1','span2')
The classList
attribute provides a DOMTokenList which has a variety of methods. You can operate on an element's classList using simple manipulations like add(), remove() or replace(). Or get very sophisticated and manipulate classes like you would an object or Map with keys(), values(), entries()
Peter Boughton's answer is a great one but it's now over a decade old. All modern browsers now support DOMTokenList - see https://caniuse.com/#search=classList and even IE11 supports some DOMTokenList methods
Yes there is many ways to do this. In ES6 syntax we can achieve easily. Use this code toggle add and remove class.
const tabs=document.querySelectorAll('.menu li');_x000D_
_x000D_
for(let tab of tabs){_x000D_
_x000D_
tab.onclick=function(){_x000D_
_x000D_
let activetab=document.querySelectorAll('li.active');_x000D_
_x000D_
activetab[0].classList.remove('active')_x000D_
_x000D_
tab.classList.add('active'); _x000D_
}_x000D_
_x000D_
}
_x000D_
body {_x000D_
padding:20px;_x000D_
font-family:sans-serif; _x000D_
}_x000D_
_x000D_
ul {_x000D_
margin:20px 0;_x000D_
list-style:none;_x000D_
}_x000D_
_x000D_
li {_x000D_
background:#dfdfdf;_x000D_
padding:10px;_x000D_
margin:6px 0;_x000D_
cursor:pointer;_x000D_
}_x000D_
_x000D_
li.active {_x000D_
background:#2794c7;_x000D_
font-weight:bold;_x000D_
color:#ffffff;_x000D_
}
_x000D_
<i>Please click an item:</i>_x000D_
_x000D_
<ul class="menu">_x000D_
<li class="active"><span>Three</span></li>_x000D_
<li><span>Two</span></li>_x000D_
<li><span>One</span></li>_x000D_
</ul>
_x000D_
classList
DOM API:A very convenient manner of adding and removing classes is the classList
DOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using javascript. For example:
const el = document.getElementById("main");_x000D_
console.log(el.classList);
_x000D_
<div class="content wrapper animated" id="main"></div>
_x000D_
We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface DOMTokenList, an interface which is used in the DOM to represent a set of space separated tokens (like classes).
const el = document.getElementById('container');_x000D_
_x000D_
_x000D_
function addClass () {_x000D_
el.classList.add('newclass');_x000D_
}_x000D_
_x000D_
_x000D_
function replaceClass () {_x000D_
el.classList.replace('foo', 'newFoo');_x000D_
}_x000D_
_x000D_
_x000D_
function removeClass () {_x000D_
el.classList.remove('bar');_x000D_
}
_x000D_
button{_x000D_
margin: 20px;_x000D_
}_x000D_
_x000D_
.foo{_x000D_
color: red;_x000D_
}_x000D_
_x000D_
.newFoo {_x000D_
color: blue;_x000D_
}_x000D_
_x000D_
.bar{_x000D_
background-color:powderblue;_x000D_
}_x000D_
_x000D_
.newclass{_x000D_
border: 2px solid green;_x000D_
}
_x000D_
<div class="foo bar" id="container">_x000D_
"Sed ut perspiciatis unde omnis _x000D_
iste natus error sit voluptatem accusantium doloremque laudantium, _x000D_
totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et _x000D_
quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam _x000D_
voluptatem quia voluptas _x000D_
</div>_x000D_
_x000D_
<button onclick="addClass()">AddClass</button>_x000D_
_x000D_
<button onclick="replaceClass()">ReplaceClass</button>_x000D_
_x000D_
<button onclick="removeClass()">removeClass</button>_x000D_
_x000D_
There is a property className in javascript to change the name of the class of an HTML element. The existing class value will be replaced with the new one, that you have assigned in className.
<!DOCTYPE html>
<html>
<head>
<title>How to change class of an HTML element in Javascript?</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br />
<center><button id="change-class">Change Class</button></center>
<script>
var change_class=document.getElementById("change-class");
change_class.onclick=function()
{
var icon=document.getElementById("icon");
icon.className="fa fa-gear";
}
</script>
</body>
</html>
Credit - https://jaischool.com/javascript-lang/how-to-change-class-name-of-an-html-element-in-javascript.html
No offense, but it's unclever to change class on-the-fly as it forces the CSS interpreter to recalculate the visual presentation of the entire web page.
The reason is that it is nearly impossible for the CSS interpreter to know if any inheritance or cascading could be changed, so the short answer is:
Never ever change className on-the-fly !-)
But usually you'll only need to change a property or two, and that is easily implemented:
function highlight(elm){
elm.style.backgroundColor ="#345";
elm.style.color = "#fff";
}
Here's my version, fully working:
function addHTMLClass(item, classname) {
var obj = item
if (typeof item=="string") {
obj = document.getElementById(item)
}
obj.className += " " + classname
}
function removeHTMLClass(item, classname) {
var obj = item
if (typeof item=="string") {
obj = document.getElementById(item)
}
var classes = ""+obj.className
while (classes.indexOf(classname)>-1) {
classes = classes.replace (classname, "")
}
obj.className = classes
}
Usage:
<tr onmouseover='addHTMLClass(this,"clsSelected")'
onmouseout='removeHTMLClass(this,"clsSelected")' >
function classed(el, class_name, add_class) {
const re = new RegExp("(?:^|\\s)" + class_name + "(?!\\S)", "g");
if (add_class && !el.className.match(re)) el.className += " " + class_name
else if (!add_class) el.className = el.className.replace(re, '');
}
using the accepted answer above here is a simple cross-browser function to add and remove class
add class:
classed(document.getElementById("denis"), "active", true)
remove class:
classed(document.getElementById("denis"), "active", false)
Lots of answers, lots of good answers.
TL;DR :
document.getElementById('id').className = 'class'
OR
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');
That's it.
And, if you really want to know the why and educate yourself then I suggest reading Peter Boughton's answer, it's perfect.
Note:
This is possible with (document or event):
getElementById()
getElementsByClassName()
querySelector()
querySelectorAll()
Here is simple jQuery code to do that.
$(".class1").click(function(argument) {
$(".parentclass").removeClass("classtoremove");
setTimeout(function (argument) {
$(".parentclass").addClass("classtoadd");
}, 100);
});
Here,
Good Luck.
You can use node.className
like so:
document.getElementById('foo').className = 'bar';
This should work in IE5.5 and up according to PPK.
Here's a toggleClass to toggle/add/remove a class on an element:
// If newState is provided add/remove theClass accordingly, otherwise toggle theClass
function toggleClass(elem, theClass, newState) {
var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');
var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));
elem.className=elem.className.replace(matchRegExp, ''); // clear all
if (add) elem.className += ' ' + theClass;
}
see jsfiddle
also see my answer here for creating a new class dynamically
You can use node.className
like so:
document.getElementById('foo').className = 'bar';
This should work in IE5.5 and up according to PPK.
Using pure JavaScript code:
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
if (!this.hasClass(ele, cls)) ele.className += " " + cls;
}
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ');
}
}
function replaceClass(ele, oldClass, newClass){
if(hasClass(ele, oldClass)){
removeClass(ele, oldClass);
addClass(ele, newClass);
}
return;
}
function toggleClass(ele, cls1, cls2){
if(hasClass(ele, cls1)){
replaceClass(ele, cls1, cls2);
}else if(hasClass(ele, cls2)){
replaceClass(ele, cls2, cls1);
}else{
addClass(ele, cls1);
}
}
Here is a little style vs. classList examples to get you to see what are the options you have available and how to use classList
to do what you want.
style
vs. classList
The difference between style
and classList
is that with style
you're adding to the style properties of the element, but classList
is kinda controlling the class(es) of the element (add
, remove
, toggle
, contain
), I will show you how to use the add
and remove
method since those are the popular ones.
If you want to add margin-top
property into an element, you would do in such:
// Get the Element
const el = document.querySelector('#element');
// Add CSS property
el.style.margintop = "0px"
el.style.margintop = "25px" // This would add a 25px to the top of the element.
Let say we have a <div class="class-a class-b">
, in this case, we have 2 classes added to our div element already, class-a
and class-b
, and we want to control what classes remove
and what class to add
. This is where classList
becomes handy.
class-b
// Get the Element
const el = document.querySelector('#element');
// Remove class-b style from the element
el.classList.remove("class-b")
class-c
// Get the Element
const el = document.querySelector('#element');
// Add class-b style from the element
el.classList.add("class-c")
This is easiest with a library like jQuery:
<input type="button" onClick="javascript:test_byid();" value="id='second'" />
<script>
function test_byid()
{
$("#second").toggleClass("highlight");
}
</script>
Working JavaScript code:
<div id="div_add" class="div_add">Add class from Javascript</div>
<div id="div_replace" class="div_replace">Replace class from Javascript</div>
<div id="div_remove" class="div_remove">Remove class from Javascript</div>
<button onClick="div_add_class();">Add class from Javascript</button>
<button onClick="div_replace_class();">Replace class from Javascript</button>
<button onClick="div_remove_class();">Remove class from Javascript</button>
<script type="text/javascript">
function div_add_class()
{
document.getElementById("div_add").className += " div_added";
}
function div_replace_class()
{
document.getElementById("div_replace").className = "div_replaced";
}
function div_remove_class()
{
document.getElementById("div_remove").className = "";
}
</script>
You can download a working code from this link.
Here is a little style vs. classList examples to get you to see what are the options you have available and how to use classList
to do what you want.
style
vs. classList
The difference between style
and classList
is that with style
you're adding to the style properties of the element, but classList
is kinda controlling the class(es) of the element (add
, remove
, toggle
, contain
), I will show you how to use the add
and remove
method since those are the popular ones.
If you want to add margin-top
property into an element, you would do in such:
// Get the Element
const el = document.querySelector('#element');
// Add CSS property
el.style.margintop = "0px"
el.style.margintop = "25px" // This would add a 25px to the top of the element.
Let say we have a <div class="class-a class-b">
, in this case, we have 2 classes added to our div element already, class-a
and class-b
, and we want to control what classes remove
and what class to add
. This is where classList
becomes handy.
class-b
// Get the Element
const el = document.querySelector('#element');
// Remove class-b style from the element
el.classList.remove("class-b")
class-c
// Get the Element
const el = document.querySelector('#element');
// Add class-b style from the element
el.classList.add("class-c")
Change an element's CSS class with JavaScript in ASP.NET:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
lbSave.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")
lbSave.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")
lbCancel.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")
lbCancel.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")
End If
End Sub
try
element.className='second'
function change(box) { box.className='second' }
_x000D_
.first { width: 70px; height: 70px; background: #ff0 }_x000D_
.second { width: 150px; height: 150px; background: #f00; transition: 1s }
_x000D_
<div onclick="change(this)" class="first">Click me</div>
_x000D_
Here is simple jQuery code to do that.
$(".class1").click(function(argument) {
$(".parentclass").removeClass("classtoremove");
setTimeout(function (argument) {
$(".parentclass").addClass("classtoadd");
}, 100);
});
Here,
Good Luck.
Here's my version, fully working:
function addHTMLClass(item, classname) {
var obj = item
if (typeof item=="string") {
obj = document.getElementById(item)
}
obj.className += " " + classname
}
function removeHTMLClass(item, classname) {
var obj = item
if (typeof item=="string") {
obj = document.getElementById(item)
}
var classes = ""+obj.className
while (classes.indexOf(classname)>-1) {
classes = classes.replace (classname, "")
}
obj.className = classes
}
Usage:
<tr onmouseover='addHTMLClass(this,"clsSelected")'
onmouseout='removeHTMLClass(this,"clsSelected")' >
Wow, surprised there are so many overkill answers here...
<div class="firstClass" onclick="this.className='secondClass'">
I use the following vanilla JavaScript functions in my code. They use regular expressions and indexOf
but do not require quoting special characters in regular expressions.
function addClass(el, cn) {
var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
c1 = (" " + cn + " ").replace(/\s+/g, " ");
if (c0.indexOf(c1) < 0) {
el.className = (c0 + c1).replace(/\s+/g, " ").replace(/^ | $/g, "");
}
}
function delClass(el, cn) {
var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
c1 = (" " + cn + " ").replace(/\s+/g, " ");
if (c0.indexOf(c1) >= 0) {
el.className = c0.replace(c1, " ").replace(/\s+/g, " ").replace(/^ | $/g, "");
}
}
You can also use element.classList in modern browsers.
No offense, but it's unclever to change class on-the-fly as it forces the CSS interpreter to recalculate the visual presentation of the entire web page.
The reason is that it is nearly impossible for the CSS interpreter to know if any inheritance or cascading could be changed, so the short answer is:
Never ever change className on-the-fly !-)
But usually you'll only need to change a property or two, and that is easily implemented:
function highlight(elm){
elm.style.backgroundColor ="#345";
elm.style.color = "#fff";
}
I would use jQuery and write something like this:
jQuery(function($) {
$("#some-element").click(function() {
$(this).toggleClass("clicked");
});
});
This code adds a function to be called when an element of the id some-element is clicked. The function appends clicked to the element's class attribute if it's not already part of it, and removes it if it's there.
Yes you do need to add a reference to the jQuery library in your page to use this code, but at least you can feel confident the most functions in the library would work on pretty much all the modern browsers, and it will save you time implementing your own code to do the same.
Thanks
This is working for me:
function setCSS(eleID) {
var currTabElem = document.getElementById(eleID);
currTabElem.setAttribute("class", "some_class_name");
currTabElem.setAttribute("className", "some_class_name");
}
Yes there is many ways to do this. In ES6 syntax we can achieve easily. Use this code toggle add and remove class.
const tabs=document.querySelectorAll('.menu li');_x000D_
_x000D_
for(let tab of tabs){_x000D_
_x000D_
tab.onclick=function(){_x000D_
_x000D_
let activetab=document.querySelectorAll('li.active');_x000D_
_x000D_
activetab[0].classList.remove('active')_x000D_
_x000D_
tab.classList.add('active'); _x000D_
}_x000D_
_x000D_
}
_x000D_
body {_x000D_
padding:20px;_x000D_
font-family:sans-serif; _x000D_
}_x000D_
_x000D_
ul {_x000D_
margin:20px 0;_x000D_
list-style:none;_x000D_
}_x000D_
_x000D_
li {_x000D_
background:#dfdfdf;_x000D_
padding:10px;_x000D_
margin:6px 0;_x000D_
cursor:pointer;_x000D_
}_x000D_
_x000D_
li.active {_x000D_
background:#2794c7;_x000D_
font-weight:bold;_x000D_
color:#ffffff;_x000D_
}
_x000D_
<i>Please click an item:</i>_x000D_
_x000D_
<ul class="menu">_x000D_
<li class="active"><span>Three</span></li>_x000D_
<li><span>Two</span></li>_x000D_
<li><span>One</span></li>_x000D_
</ul>
_x000D_
In one of my old projects that did not use jQuery, I built the following functions for adding, removing and checking if element has class:
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
if (!hasClass(ele, cls)) ele.className += " " + cls;
}
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ');
}
}
So, for example, if I want onclick
to add some class to the button I can use this:
<script type="text/javascript">
function changeClass(btn, cls) {
if(!hasClass(btn, cls)) {
addClass(btn, cls);
}
}
</script>
...
<button onclick="changeClass(this, "someClass")">My Button</button>
By now for sure it would just be better to use jQuery.
classList
DOM API:A very convenient manner of adding and removing classes is the classList
DOM API. This API allows us to select all classes of a specific DOM element in order to modify the list using javascript. For example:
const el = document.getElementById("main");_x000D_
console.log(el.classList);
_x000D_
<div class="content wrapper animated" id="main"></div>
_x000D_
We can observe in the log that we are getting back an object with not only the classes of the element, but also many auxiliary methods and properties. This object inherits from the interface DOMTokenList, an interface which is used in the DOM to represent a set of space separated tokens (like classes).
const el = document.getElementById('container');_x000D_
_x000D_
_x000D_
function addClass () {_x000D_
el.classList.add('newclass');_x000D_
}_x000D_
_x000D_
_x000D_
function replaceClass () {_x000D_
el.classList.replace('foo', 'newFoo');_x000D_
}_x000D_
_x000D_
_x000D_
function removeClass () {_x000D_
el.classList.remove('bar');_x000D_
}
_x000D_
button{_x000D_
margin: 20px;_x000D_
}_x000D_
_x000D_
.foo{_x000D_
color: red;_x000D_
}_x000D_
_x000D_
.newFoo {_x000D_
color: blue;_x000D_
}_x000D_
_x000D_
.bar{_x000D_
background-color:powderblue;_x000D_
}_x000D_
_x000D_
.newclass{_x000D_
border: 2px solid green;_x000D_
}
_x000D_
<div class="foo bar" id="container">_x000D_
"Sed ut perspiciatis unde omnis _x000D_
iste natus error sit voluptatem accusantium doloremque laudantium, _x000D_
totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et _x000D_
quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam _x000D_
voluptatem quia voluptas _x000D_
</div>_x000D_
_x000D_
<button onclick="addClass()">AddClass</button>_x000D_
_x000D_
<button onclick="replaceClass()">ReplaceClass</button>_x000D_
_x000D_
<button onclick="removeClass()">removeClass</button>_x000D_
_x000D_
OK, I think in this case you should use jQuery or write your own Methods in pure javascript, my preference is adding my own methods rather than injecting all jQuery to my application if I don't need that for other reasons.
I'd like to do something like below as methods to my javascript framework to add few functionalities which handle adding classes, deleting classes, etc similar to jQuery, this is fully supported in IE9+, also my code is written in ES6, so you need to make sure your browser support it or you using something like babel, otherwise need to use ES5 syntax in your code, also in this way, we finding element via ID, which means the element needs to have an ID to be selected:
//simple javascript utils for class management in ES6
var classUtil = {
addClass: (id, cl) => {
document.getElementById(id).classList.add(cl);
},
removeClass: (id, cl) => {
document.getElementById(id).classList.remove(cl);
},
hasClass: (id, cl) => {
return document.getElementById(id).classList.contains(cl);
},
toggleClass: (id, cl) => {
document.getElementById(id).classList.toggle(cl);
}
}
and you can simply call use them as below, imagine your element has id of 'id' and class of 'class', make sure you pass them as a string, you can use the util as below:
classUtil.addClass('myId', 'myClass');
classUtil.removeClass('myId', 'myClass');
classUtil.hasClass('myId', 'myClass');
classUtil.toggleClass('myId', 'myClass');
You could also just do:
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');
And to toggle a class (remove if exists else add it):
document.getElementById('id').classList.toggle('class');
Just to add on information from another popular framework, Google Closures, see their dom/classes class:
goog.dom.classes.add(element, var_args)
goog.dom.classes.addRemove(element, classesToRemove, classesToAdd)
goog.dom.classes.remove(element, var_args)
One option for selecting the element is using goog.dom.query with a CSS3 selector:
var myElement = goog.dom.query("#MyElement")[0];
OK, I think in this case you should use jQuery or write your own Methods in pure javascript, my preference is adding my own methods rather than injecting all jQuery to my application if I don't need that for other reasons.
I'd like to do something like below as methods to my javascript framework to add few functionalities which handle adding classes, deleting classes, etc similar to jQuery, this is fully supported in IE9+, also my code is written in ES6, so you need to make sure your browser support it or you using something like babel, otherwise need to use ES5 syntax in your code, also in this way, we finding element via ID, which means the element needs to have an ID to be selected:
//simple javascript utils for class management in ES6
var classUtil = {
addClass: (id, cl) => {
document.getElementById(id).classList.add(cl);
},
removeClass: (id, cl) => {
document.getElementById(id).classList.remove(cl);
},
hasClass: (id, cl) => {
return document.getElementById(id).classList.contains(cl);
},
toggleClass: (id, cl) => {
document.getElementById(id).classList.toggle(cl);
}
}
and you can simply call use them as below, imagine your element has id of 'id' and class of 'class', make sure you pass them as a string, you can use the util as below:
classUtil.addClass('myId', 'myClass');
classUtil.removeClass('myId', 'myClass');
classUtil.hasClass('myId', 'myClass');
classUtil.toggleClass('myId', 'myClass');
You could also just do:
document.getElementById('id').classList.add('class');
document.getElementById('id').classList.remove('class');
And to toggle a class (remove if exists else add it):
document.getElementById('id').classList.toggle('class');
just say myElement.classList="new-class"
unless you need to maintain other existing classes in which case you can use the classList.add, .remove
methods.
var doc = document;_x000D_
var divOne = doc.getElementById("one");_x000D_
var goButton = doc.getElementById("go");_x000D_
_x000D_
goButton.addEventListener("click", function() {_x000D_
divOne.classList="blue";_x000D_
});
_x000D_
div{_x000D_
min-height:48px;_x000D_
min-width:48px;_x000D_
}_x000D_
.bordered{_x000D_
border: 1px solid black;_x000D_
}_x000D_
.green{_x000D_
background:green;_x000D_
}_x000D_
.blue{_x000D_
background: blue;_x000D_
}
_x000D_
<button id="go">Change Class</button>_x000D_
_x000D_
<div id="one" class="bordered green">_x000D_
_x000D_
</div>
_x000D_
There is a property className in javascript to change the name of the class of an HTML element. The existing class value will be replaced with the new one, that you have assigned in className.
<!DOCTYPE html>
<html>
<head>
<title>How to change class of an HTML element in Javascript?</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br />
<center><button id="change-class">Change Class</button></center>
<script>
var change_class=document.getElementById("change-class");
change_class.onclick=function()
{
var icon=document.getElementById("icon");
icon.className="fa fa-gear";
}
</script>
</body>
</html>
Credit - https://jaischool.com/javascript-lang/how-to-change-class-name-of-an-html-element-in-javascript.html
You may try to use node attributes
property to keep compatibility with old browsers even IE6:
function getClassNode(element) {_x000D_
for (var i = element.attributes.length; i--;)_x000D_
if (element.attributes[i].nodeName === 'class')_x000D_
return element.attributes[i];_x000D_
}_x000D_
_x000D_
function removeClass(classNode, className) {_x000D_
var index, classList = classNode.value.split(' ');_x000D_
if ((index = classList.indexOf(className)) > -1) {_x000D_
classList.splice(index, 1);_x000D_
classNode.value = classList.join(' ');_x000D_
}_x000D_
}_x000D_
_x000D_
function hasClass(classNode, className) {_x000D_
return classNode.value.indexOf(className) > -1;_x000D_
}_x000D_
_x000D_
function addClass(classNode, className) {_x000D_
if (!hasClass(classNode, className))_x000D_
classNode.value += ' ' + className;_x000D_
}_x000D_
_x000D_
document.getElementById('message').addEventListener('click', function() {_x000D_
var classNode = getClassNode(this);_x000D_
var className = hasClass(classNode, 'red') && 'blue' || 'red';_x000D_
_x000D_
removeClass(classNode, 'red');_x000D_
removeClass(classNode, 'blue');_x000D_
_x000D_
addClass(classNode, className);_x000D_
})
_x000D_
.red {_x000D_
color: red;_x000D_
}_x000D_
.red:before {_x000D_
content: 'I am red! ';_x000D_
}_x000D_
.red:after {_x000D_
content: ' again';_x000D_
}_x000D_
.blue {_x000D_
color: blue;_x000D_
}_x000D_
.blue:before {_x000D_
content: 'I am blue! '_x000D_
}
_x000D_
<span id="message" class="">Click me</span>
_x000D_
Change an element's CSS class with JavaScript in ASP.NET:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
lbSave.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")
lbSave.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")
lbCancel.Attributes.Add("onmouseover", "this.className = 'LinkButtonStyle1'")
lbCancel.Attributes.Add("onmouseout", "this.className = 'LinkButtonStyle'")
End If
End Sub
Just thought I'd throw this in:
function inArray(val, ary){
for(var i=0,l=ary.length; i<l; i++){
if(ary[i] === val){
return true;
}
}
return false;
}
function removeClassName(classNameS, fromElement){
var x = classNameS.split(/\s/), s = fromElement.className.split(/\s/), r = [];
for(var i=0,l=s.length; i<l; i++){
if(!iA(s[i], x))r.push(s[i]);
}
fromElement.className = r.join(' ');
}
function addClassName(classNameS, toElement){
var s = toElement.className.split(/\s/);
s.push(c); toElement.className = s.join(' ');
}
I use the following vanilla JavaScript functions in my code. They use regular expressions and indexOf
but do not require quoting special characters in regular expressions.
function addClass(el, cn) {
var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
c1 = (" " + cn + " ").replace(/\s+/g, " ");
if (c0.indexOf(c1) < 0) {
el.className = (c0 + c1).replace(/\s+/g, " ").replace(/^ | $/g, "");
}
}
function delClass(el, cn) {
var c0 = (" " + el.className + " ").replace(/\s+/g, " "),
c1 = (" " + cn + " ").replace(/\s+/g, " ");
if (c0.indexOf(c1) >= 0) {
el.className = c0.replace(c1, " ").replace(/\s+/g, " ").replace(/^ | $/g, "");
}
}
You can also use element.classList in modern browsers.
function classed(el, class_name, add_class) {
const re = new RegExp("(?:^|\\s)" + class_name + "(?!\\S)", "g");
if (add_class && !el.className.match(re)) el.className += " " + class_name
else if (!add_class) el.className = el.className.replace(re, '');
}
using the accepted answer above here is a simple cross-browser function to add and remove class
add class:
classed(document.getElementById("denis"), "active", true)
remove class:
classed(document.getElementById("denis"), "active", false)
This is easiest with a library like jQuery:
<input type="button" onClick="javascript:test_byid();" value="id='second'" />
<script>
function test_byid()
{
$("#second").toggleClass("highlight");
}
</script>
Source: Stackoverflow.com