How can I add a class to an element using JavaScript?

I have a <div> element that already contains a class, like this:

<div class="someclass">
    <img ... id="image1" name="image1" />
</div>

Now, I want to write a JavaScript function that will add a class to this <div> without replacing the existing class. How can I achieve this with add class javascript?

Hey, I’ve worked with DOM manipulation quite a bit, and honestly, the easiest and most modern approach is using classList.add(). This method is part of the classList API, which was introduced specifically to make class manipulations like add class javascript straightforward and clean.

function addClass() {
  const div = document.querySelector('.someclass');
  div.classList.add('newclass');
}

This will add the newclass without touching the existing someclass. No messy string handling, no risk of duplicate classes — it’s really the go-to method these days.

That’s a solid starting point, Miro! From my experience maintaining legacy projects, sometimes you can’t rely on classList because of older browser support or existing code patterns. In those cases, you can fall back on directly manipulating the className property. It’s a more traditional method for add class javascript, but still perfectly functional if you handle it carefully:

function addClass() {
  const div = document.querySelector('.someclass');
  div.className += ' newclass';
}

The key here is making sure you include the space before the new class, so you don’t smash the words together. It’s more manual, but gives you a bit more transparency if you’re working on simpler or older setups.

Great points, both of you! I’ve often found that when you need maximum control — maybe you’re interacting with dynamic attributes or custom class setups — using getAttribute() and setAttribute() gives you the most flexibility for add class javascript tasks.

function addClass() {
  const div = document.querySelector('.someclass');
  let currentClass = div.getAttribute('class');
  div.setAttribute('class', currentClass + ' newclass');
}

With this approach, you’re directly fetching and updating the raw class attribute, which can be handy if you’re juggling multiple attributes or doing some string processing before applying the class. It’s more verbose, but gives you fine-grained control over what’s happening under the hood.