-3

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?

reidm
  • 19
  • 3

2 Answers2

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