We can add a style to an element by using the
style property of an object.
To style an element, first we have to get the element that we want to style.
We can do this easily with
document.querySelector, which takes a string with any CSS selector.
For instance, if we have the following div:
We can get div by the class. We can write:
const el = document.querySelector('.foo');
to get the div element with the class
foo that we have above.
Then we can set the styles according to the properties list below at MDN.
For instance, if we want to set the color of the content inside the div we have above, we can set the
color property as follows:
el.style.color = 'green';
The code above sets the
color property of the
style property to
This will turn the text in the div green.