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

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.