Is there a way to add a second class to an HTML tag using javascript? For example, say you had the element <p class="a">
and you wanted to add class="b". If you used document.getElementByClassName("a").class = "b"
that would remove class "a". Is there a way to have both in the same element?
Asked
Active
Viewed 100 times
-3

reidm
- 19
- 3
2 Answers
1
document.getElementsByClassName("a")[0].className += " b"
First of all, the method is named getElementsByClassName
, plural. You need to refer to a specific element in the collection that it returns, via a zero-based index.
And you need the space before b
here, so that you don’t end up with ab
, but a b
.

CBroe
- 91,630
- 14
- 92
- 150
-
1You need to use `className`, not `class` – bumpy Aug 23 '15 at 22:19
-
@bumpy: You’re right of course, don’t know how I missed that. – CBroe Aug 24 '15 at 05:55
0
Try this one here:
document.getElementByClassName("a").className += " b"
Got it from here: How do I add a class to a given element?

Community
- 1
- 1

HelloWorld
- 2,392
- 3
- 31
- 68