Querying the DOM - Element Styles

Let's go back to our button and try to access and change its style. To get its style, we can use the style property:

let button = document.getElementById("hello");
button.style;

You should get a CSSProperties object.

To access a particular property, use dot notation again to access the property. Here are some common ones:

let element = document.querySelector(query);
element.style.color; // returns the color of the element
element.style.border; // returns the border specification of the element
element.style.backgroundColor; // returns the background color

In general, element.style.propertyName should return the value for that property.

One small problem

If you actually run the above code to get a property of the element (say, the background-color), you instead get an empty string "" rather than the value you specified in the CSS file. This is because JS, when searching for an element's style, looks at the element's style attribute. This attribute allows you to define inline CSS for an element, but it is not good practice to use it since it mixes HTML and CSS.

However, this doesn't stop us from changing the style as we see fit. Select the button from the console as before, and run the following:

button.style.backgroundColor = "red"; // or any other color value you like

You'll see the button color changes to red.

If you navigate to the Inspector and select the button, you'll also see that it now has a new style attribute that wasn't there before:

<button id="hello" onclick="alert('Hello!')" style="background-color: red;">...</button>

You can do the same with any style properties by getting/setting their values to any (valid) values as you like.

To reset the value back to normal, simply assign the empty string:

button.style.backgroundColor = "";

This removes the inline styling for that property of the button which sets it back to its original style.

Note that for the style values to change, they must be valid CSS values and must be assigned as strings.

Here's how this looks on the page:

Next steps

Next, we'll look at adding JS to our html pages to make it more interactive.

Last updated