I have an element that already has a class:
You can use modern approach similar to jQuery
If you need to change only one element, first one that JS will find in DOM, you can use this:
document.querySelector('.someclass').className += " red";
.red {
color: red;
}
This method will add class "red" only to first element in DOM
lorem ipsum
lorem ipsum
lorem ipsum
Keep in mind to leave one space before class name.
If you have multiple classes where you want to add new class, you can use it like this
document.querySelectorAll('.someclass').forEach(function(element) {
element.className += " red";
});
.red {
color: red;
}
This method will add class "red" to all elements in DOM that have "someclass" class.
lorem ipsum
lorem ipsum
lorem ipsum