-1

I'm trying to add a new class to a given class without using GetElementById. My project has an array on the list, and each list creates dynamic classes like 0-test, 1-test, 2-testing, so on. Add a new class to a given class like ( 0-test active-test) class. I am trying to have some javascript properties, but it is not working properly. My code is:-

document.getElementsByClassName('0-test')[0].className += "active-test";

It's not working please tell me how to add a new class?

Cœur
  • 34,719
  • 24
  • 185
  • 251
Harleen Kaur Arora
  • 1,747
  • 2
  • 18
  • 53
  • There should be a space in `"active-test"` like `" active-test"` otherwise it will get appended to some other class (probably resulting in `"0-testactive-test"`). BTW, it's better to use `classList` for this instead of `className`: `.classList.add("active-test");` – ibrahim mahrir Jan 12 '19 at 05:07
  • 1
    Better to use `document.querySelector` if you only want the first matching element. – CertainPerformance Jan 12 '19 at 05:09
  • I have already use document.querySelector('.0-test').className += " active-test"; But its return error in because classes generate dynamically in run time. – Harleen Kaur Arora Jan 12 '19 at 05:13

1 Answers1

0

Use element.classList:

var element = document.getElementsByClassName('0-test')[0];
element.classList.add("mystyle");
ibrahim mahrir
  • 29,774
  • 5
  • 43
  • 68
Monica Acha
  • 1,091
  • 8
  • 16