Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add css class using document.getElementsByClassName

Tags:

javascript

css

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].className += 'newclassname';
}

but when I tried changing background it works

var x = document.getElementsByClassName("oldclassname");
var i;
for (i = 0; i < x.length; i++) {

  x[i].style.backgroundColor = "red";
}

Am I doing anything wrong while adding css file

like image 283
Aakash Avatar asked May 18 '26 03:05

Aakash


2 Answers

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
like image 164
Alastair Brown Avatar answered May 20 '26 16:05

Alastair Brown


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>
like image 23
Oriol Avatar answered May 20 '26 17:05

Oriol