HTML DOM acronym for Document Object Model is a programming interface for documents written in HTML and XML. It provides a logical structure to the documents. HTML DOM defines how HTML documents can be evaluated and changed. Using HTML DOM you can alter the style of HTML elements through JavaScript.
The style property of HTML DOM is used for the purpose of changing the style of HTML elements.
Style Property of HTML DOM
A style attribute of an HTML element is represented by a CSSStyleDeclaration object. In order to return this CSSStyleDeclaration object, the style property is used. This property is used to either get or set the style of elements using various CSS properties.
Syntax
Syntax of the HTML DOM style property is given as follows.
If you simply want to get a style property, use the following syntax.
However if you want to set a style property, use the given syntax
Now that we have a basic understanding of what HTML DOM style property is. We will now explore some relevant examples.
Changing HTML style
The given examples demonstrate how we can change style of HTML elements using JavaScript.
Example 1
Suppose, you want to change the color of <p> element using its id.
In the above example, we first simply defined two <p> elements and assigned them a unique id.
We then changed the color of <p> element with id=”para2″. In the following piece of code where we’re simply getting our desired element by its id and changing its color to red.
document.getElementById("para2").style.color = "red";
</script>
Here is how it looked before changing the color.
After changing the color.
Example 2
Suppose, you want to change the color as well as the font-family of <h1> element using its id.
In the above example, we first simply defined two <h1> elements and assigned them a unique id.
We then changed the color and the font family of <h1> element with id=”head2″. In the following piece of code where we’re simply getting our desired element by its id and changing its color to blue and font family to arial.
GeSHi Error: GeSHi could not find the language jacascript (using path /home/nginx/domains/linuxhint.com/public/wp-content/plugins/codecolorer/lib/geshi/) (code 2)
Here is how it looked before changing the color and the font family.
After changing the color and font family it looks like this.
Conclusion
To alter the style of HTML elements using JavaScript we use the HTML DOM style property. The HTML DOM style property allows you to get or set the style of an HTML element. There can be different approaches to use this property in order to alter the style of HTML elements. This tutorial covers HTML DOM style property and different approaches that can be used to change the style of HTML elements.