Skip to content Skip to sidebar Skip to footer

Add Css Class Using Document.getElementsByClassName

I am trying to add css class using javascript but its not working var x = document.getElementsByClassName('oldclassname'); var i; for (i = 0; i < x.length; i++) { x[i].clas

Solution 1:

className is a space separated list of class names. The problem with your code is that it doesn't separate the class names with spaces. Try this:

var x = document.getElementsByClassName('oldclassname');
var i;
for (i = 0; i < x.length; i++) 
{
   x[i].className += ' newclassname'; // WITH space added
}

Without the space, it has only one class name

<div class="oldclassnamenewclassname"></div>
//if use space
<div class="oldclassname newclassname"></div>//get two class name

Solution 2:

Better use classList:

var x = document.getElementsByClassName('oldclassname');
for (var i = 0; i < x.length; i++) {
  x[i].classList.add('newclassname');
}
.newclassname { color: blue; }
<div class="oldclassname">Hello, world!</div>

Solution 3:

Hi there is a much simpler way to do this using javascript

TO add a class: -

document.getElementsByClassName('otherClassName')[0].classList.add('newClassName');

To remove a class:-

document.getElementsByClassName('otherClassName')[0].classList.remove('newClassName');

Hope this helps :)


Solution 4:

It works . Check your target class name formation. Sample Code.

<html>
<head>
<style>
.classFrom{
    font-family: sans-serif;
    color: red;
}

.classTo{
    font-family:cursive;
    color: blue;
}
</style>

<script type="text/javascript">
function clickme(){
var elmList = document.getElementsByClassName('classFrom');
  for (i = 0; i < elmList.length; i++) 
    {
       elmList[i].className += " classTo";
    }
}
</script>
</head>
<body>
<div class="classFrom">SampleText</div>
<button onClick="clickme()">ChangeCSS</button>
</body>
</html>

Post a Comment for "Add Css Class Using Document.getElementsByClassName"