← Web basics: HTML, CSS and JavaScript

Classes and attributes from JavaScript

classList.add, remove and toggle, and setAttribute.

Start this lesson

The cleanest way to change how something looks from JavaScript is to change its classes and let CSS do the styling. element.classList.add("name") adds a class, .remove("name") removes it, .toggle("name") adds it if missing and removes it if present, and .contains("name") asks whether it is there. For other attributes, element.setAttribute("alt", "A red kite") sets one and getAttribute reads it.

<style>
  .hidden { display: none; }
  .selected { background-color: gold; }
</style>

<p id="tip" class="hidden">Drink water!</p>
<img id="pic" src="day.jpg" alt="Sunny beach">

<script>
  document.querySelector("#tip").classList.remove("hidden");
  const pic = document.querySelector("#pic");
  pic.setAttribute("src", "night.jpg");
  pic.setAttribute("alt", "Beach under the stars");
</script>

Removing the class hidden makes the tip appear, because the CSS rule no longer matches. The image gets a new picture and, importantly, a new alt text that matches it.

You can also set styles directly, like element.style.color = "red". It works, but mixing looks into JavaScript gets messy; a class keeps all the looks in your CSS.

When you change an image's src, always update its alt too.