JavaScript Styling Elements

We are very fortunate that we can use JavaScript to dynamically style HTML elements. We can do this by leveraging the HTML Document Object Model (DOM). DOM provides us with the very useful Style object. The Style object
represents an individual style statement. The Style object can be accessed from the document or from the elements to which that style is applied. Here is an example of the syntax used for styling an element.

document.getElementById("id").style.property="value"

The values that you provide depend on the property. Fortunately, the values are very similar to those you would use in Cascading Style Sheets (CSS). So if you are familiar with HTML and CSS, using the DOM
Style object with JavaScript should not be too challenging for you. Here is a listing of the more common Style object properties:

Background Style Properties

Property

Description

background

Gets or sets all the background properties

backgroundAttachment

Gets or sets whether a background image is fixed or scrolls with the page

Select one of the options below to change the
text color in this paragraph.

Red
Blue
Green

You should note that the text color of the paragraph with an id of p1 changes dynamically and without the page being reloaded. As you can see, the DOM Style object can be extremely useful. A practical use case is
where you may want to change the style of different elements when wanting to catch the attention, or change the size of text on the screen. Also, its common to use these techniques when informing the user of an error
on the screen.

Please help us spread the word by socializing it today!

Did you find something wrong with the information on this page? Please take a moment to report it to us
so that we can continue to improve the quality of the information on this site. Click here to
report an issue with this page.