Javascript Change HTML Element Styles Tutorial

In this Javascipt tutorial we learn how to change HTML element styles with Javascript by accessing the style object.

We also discuss some rules when working with the style object and its properties.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

How to change HTML element styles

Now that we know how to select HTML elementsOpens up in a new page , we can perform several types of operations on them.

For example, we can manipulate and change HTML element styles with Javascript by tapping into the style object of the selected element.

The style object contains all the CSS properties we need to change a specific style on an element.

Syntax:
 element.style.property = "value";
Example:
<html>
<body>
  <h1>Heading 1</h1>
  <p>Lorem ipsum dolor sit amet</p>
</body>
<script>
  // change the h1 text color
  document.querySelector("h1").style.color = "#45C5B0";

  // change the the paragraph
  // background color and add
  // some padding
  const x = document.querySelector("p");
  x.style.backgroundColor = "gainsboro";
  x.style.padding = "1rem";
</script>
</html>

In the example above, we change the color property of the heading and add a background color and some padding to the paragraph.

Every style can be changed from Javascript, however the property names might look a little different from what we’re used to.

As mentioned in the Variables & Constants lessonOpens up in a new page , Javascript naming conventions tend to use camel case. Any properties with multiple words will use camel case instead of the dash operator.

Example:
<html>
<body>
  <h1>Heading 1</h1>
  <!-- css properties with multiple words
       use dashes to separate them        -->
  <p style="font-size: 1.2rem">Lorem ipsum dolor sit amet</p>
</body>
<script>
  // in Javascript the property name excludes
  // the dash in favor of camel casing
  // instead of font-size, we use fontSize
  document.querySelector("h1").style.fontSize = "3rem";
</script>
</html>

Another important point is that the property values must be specified as strings. If we don’t use a string, the property won’t change and Javascript will raise an error.

Example:
<html>
<body>
  <h1>Heading 1</h1>
</body>
<script>
  // will raise an error
  document.querySelector("h1").style.fontSize = 3rem;
</script>
</html>

The example above doesn’t use a string when trying to change the font size, so Javascript raises an error.

Output:
 Uncaught SyntaxError: Invalid or unexpected token

The error is a little confusing but basically it means that Javascript was expecting a " from the beginning of a string, but got something else instead.

So, if a property has multiple words, converting from CSS to Javascript is easy.

  • We remove the dash symbol
  • Convert the words to camel case
Example:
// css              javascript
font-size           fontSize
background-color    backgroundColor
border-left-color   borderLeftColor
// etc.

How to add & remove classes

When working with HTML, CSS and Javascript, we typically want a separation of concerns. What this means is that we want to separate the structure (HTML), style (CSS) and behavior (Js) from each other.

We shouldn’t change styles directly from Javascript. That would combine style and behavior, which is considered a bad practice.

Instead, we write classes in CSS and add them to an HTML element with Javascript with the classList property.

  • classList.add() will add the specified class to a selected element.
  • classList.remove() will remove the specified class from a selected element.
  • classList.toggle() will add/remove the specified class when invoked.

The add() method takes the class name we want to add as an argument.

Syntax:
 element.classList.add("class_name");
Example:
<html>
  <style>
    body { display: flex; flex-direction: column; justify-content: center; align-items: center }
    div { width: 10rem; margin: 1rem; padding: 1.5rem; border: .2rem solid #45B0E5; background: #71D0FF; }
    button { width: 10rem; padding: 1rem; border: .1rem solid #eeeeee;  text-align: center; background: #fff }
    .hidden { display: none }
  </style>
<body>
  <div></div>
  <button>Click me!</button>
</body>
<script>
  // select div element
  const x = document.getElementsByTagName("div");

  // add the 'hidden' class to
  // the element's class list
  function hide() {

    x[0].classList.add("hidden");
  }

  // add an event
  document.querySelector("button").addEventListener("click", hide);
</script>
</html>

In the example above, the ‘.hidden’ class will hide whichever element it’s attached to. In the hide() function we tell Javascript that we want to add this class to the div element.

In the last statement we add an event listener to the button that will invoke the hide() function when the button is clicked.

If you don’t know about event listeners, don’t worry about it for now. We cover them later on in the Event Listeners lessonOpens up in a new page .

We can also remove a class from an element with the remove() method. This method takes the class name we want to remove as an argument.

Syntax:
 element.classList.remove("class_name");
Example:
<html>
  <style>
    body { display: flex; flex-direction: column; justify-content: center; align-items: center }
    div { width: 10rem; margin: 1rem; padding: 1.5rem; border: .2rem solid #45B0E5; background: #71D0FF; }
    button { width: 10rem; padding: 1rem; border: .1rem solid #eeeeee;  text-align: center; background: #fff }
    .hidden { display: none }
  </style>
<body>
  <div class="hidden"></div>
  <button>Click me!</button>

</body>
<script>
  // select div element
  const x = document.getElementsByTagName("div");

  // remove the hidden class
  // from the 'div' element
  function show() {

    x[0].classList.remove("hidden");
  }

  // add an event
  document.querySelector("button").addEventListener("click", show);
</script>
</html>

This time, the ‘.hidden’ class is already set on the div element. In the show() function we remove the class from the div.

If we want to be able to toggle the div, we can use the toggle() method. This method will remember the previous state and reverse it.

Syntax:
 element.classList.toggle("class_name");
Example:
<html>
  <style>
    body { display: flex; flex-direction: column; justify-content: center; align-items: center }
    div { width: 10rem; margin: 1rem; padding: 1.5rem; border: .2rem solid #45B0E5; background: #71D0FF; }
    button { width: 10rem; padding: 1rem; border: .1rem solid #eeeeee;  text-align: center; background: #fff }
    .hidden { display: none }
  </style>
<body>
  <div></div>
  <button>Click me!</button>
</body>
<script>
  // select div element
  const x = document.getElementsByTagName("div");

  // add/remove the class when invoked
  function hide() {

    x[0].classList.toggle("hidden");
  }

  // add an event
  document.querySelector("button").addEventListener("click", hide);
</script>
</html>

Each time we click the button, it will either add or remove the class based on the previous state.

This is useful in things like navigation menu’s that are toggled with a button or tooltips that are toggled on a mouseover event.

Summary: Points to remember

  • We can change an HTML elements style by accessing the style object’s properties and modifying them.
    • Property names are the same as those in css except the don’t have a dash symbol connecting them and are camel cased.
    • Property values must always be specified as strings, meaning they must be within quotes.
  • Changing style elements directly with Javascript is considered a bad practice, we want to keep our CSS and Javascript as separate as we can.