Styling HTML Elements with JavaScript

OpenJavaScript 0
Reading Time: 4 minutes 🕑

Last updated: August 25, 2022.

Using JavaScript, you can style HTML elements by changing the styles on elements directly.

Alternatively, you can change styles associated with an element by editing its class list, and thus the CSS styles associated with it.

In general, the second method is favoured because it allows styles to be centralized in CSS. This allows for site-wide changes to be implemented when the style sheet is updated.

In this tutorial, we cover all of the ways you can edit the styles of a HTML element with JavaScript.

Table of contents

Editing styles directly on an element

The simplest way to set styles directly on an element is by setting a value for its style property. The value should be valid CSS syntax:

// Create element
const div = document.createElement('div');
div.textContent = "I can be styled directly";

// Set style property
div.style = "color: red; font-size: 3rem;";

// Append to DOM
document.body.append(div);

If you use template literal syntax, you can spread styling over multiple lines without the need for any special syntax, just like in CSS:

const div = document.createElement('div');
div.textContent = "I can be styled directly";

div.style = `
        color: red;
        font-size: 3rem;
        width: 100%;
        display: flex;
        justify-content: center;
`;

document.body.append(div);

A potential problem with this approach is that setting the style property directly overwrites any previous styling that was applied to the element in JavaScript.

For this reason, the more nuanced approach of setting property styles that exist on the style property is often preferred.

These styles are accessible via camel case on the style property:

const div = document.createElement('div');
div.textContent = "I can be styled directly";

div.style.color = 'red';
div.style.fontSize = '3rem';
div.style.width = '100%';
div.style.display = 'flex';
div.style.justifyContent = 'center';

document.body.append(div);

Now, more styling can be added in the same way without overwriting styles that have already been applied with JavaScript.

Editing styles via the class list attribute

Why is this approach preferred?

Styles associated with an element can be changed by editing its class list attribute.

The advantage of this approach is twofold.

First, the styling of all elements containing an item on their class list can be changed simultaneously by editing styles associated with a class name in CSS.

Second, it minimizes DOM content, keeping the size of yout HTML file to a minimum.

Practical examples

You can use classList.add(), classList.remove() and classList.toggle() to edit the contents of a class list.

The following code adds styling to a new element by using classList.add() to add the my-card class to a new element that is then added to the DOM:

<style> 
    .my-card { 
        display: block;
        margin: 0px auto;
        background-color: whitesmoke;
        padding: 2rem;
        font-size: 2rem;
        color: grey;
        text-align: center;
    } 
</style>

<script>

// Create element
const div = document.createElement('div');
div.textContent = "Add a class name to change my appearance";

// Add styling via adding class list item
div.classList.add('my-card');

// Append to DOM
document.body.append(div);

</script>

In this next example, classList.toggle() adds and remove the no-display class to the element when a button is clicked:

<style> 
    .no-display {
        display: none !important;
    }
    .my-card { 
        display: block;
        margin: 0px auto;
        background-color: whitesmoke;
        padding: 2rem;
        font-size: 2rem;
        color: grey;
        text-align: center;
    } 
</style>

<script>

// Create element
const div = document.createElement('div');
div.textContent = "Click the button to toggle my display value";

// Add bg-red to class attribute
div.classList.add('my-card');

// Create toggle display button
const btn = document.createElement('button');
btn.textContent = "Click me!";
btn.addEventListener('click', () => {
    div.classList.toggle('no-display');
});

// Append to DOM
document.body.append(btn);
document.body.append(div);

</script>

If you want to set an entirely new value for the class attribute, set a new value for the className property on the element:

// Create element
const div = document.createElement('div');
div.textContent = "Give me a new class attribute value";

// Add bg-red to class attribute
div.className = 'my-card m-3 bordered';

console.log(div);
// 
Give me a new class attribute value

Checking styles with getComputedStyle()

Sometimes, you may want to check the styles that are currently being applied to an existing element in the DOM.

For example, you may want to check if an element is currently visible to a user (see our AdBlocker detection tutorial for a practical example).

You can check the styles currently applied to a HTML element by calling window.getComputedStyle() and passing in the element you want to check.

For example, you may want to check if an element is currently visible in the DOM by checking the value of the display property:

const div = document.createElement('div');
div.textContent = "Once I am in the DOM, you can check out my styles";

document.body.append(div);

// Get current styles
const currentStyles = window.getComputedStyle(div);

// Check style values
console.log(currentStyles.getPropertyValue('display')); // block

Note that getComputedStyle() returns live styles that are currently being applied to an element in the DOM.

If an element only exists in JavaScript, all values will return an empty string.

Summary

Using JavaScript, you can style a HTML element via one of two approaches:

  • Directly on a HTML element:
    • All styles can be set by setting a value for the style attribute
    • Individual styles can be set by accessing properties on the style attribute (e.g. style.backgroundColor, style.fontSize)
  • By changing the CSS applied to an element by editings its class attribute:
    • Add: classList.add()
    • Remove: classList.remove()
    • Toggle: classList.toggle()
    • You can set a new list value by setting className

To check the styles currently applied to an element, call getComputedStyle() on the element. Then, apply getPropertyValue('styleProperty') to the result to return the current style value.

Related links