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:
You should get a CSSProperties
object.
To access a particular property, use dot notation again to access the property. Here are some common ones:
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:
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:
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:
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