2

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

Igor Ivancha
  • 3,413
  • 4
  • 30
  • 39
Aakash
  • 155
  • 1
  • 3
  • 11
  • 1
    @alastair brown's answer is correct. You also have the option to avoid dealing with spaces in `className` by using [Element.classList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList). Your code would then be `[i].classList.add('newclassname')` – Max Heiber Jun 10 '16 at 02:49

4 Answers4

7

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
Alastair Brown
  • 1,598
  • 8
  • 12
5

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>
Oriol
  • 274,082
  • 63
  • 437
  • 513
4

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 :)

Akshay Bhat
  • 284
  • 1
  • 10
0

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>
  • This removes previous classes. This is clearly undesired because the question uses `+=` instead of `=`. – Oriol Jun 10 '16 at 02:51