The HTML DOM enables JavaScript to modify the styles of HTML elements.
To modify the style of an HTML element, use the following syntax:
document.getElementById(id).style.property = new style |
The following example modifies the style of a <p> element:
<html> <body> <p id=”p2″>Hello World!</p> <script> document.getElementById(“p2”).style.color = “blue”; </script> </body> </html> |
The HTML DOM enables you to execute code in response to events.
Events are triggered by the browser when certain actions occur on HTML elements, such as:
You will learn more about events in the next chapter of this tutorial.
This example changes the style of the HTML element with id=”id1″ when the user clicks a button:
<!DOCTYPE html> <html> <body> <h1 id=”id1″>My Heading 1</h1> <button type=”button” onclick=”document.getElementById(‘id1’).style.color = ‘red'”> Click Me!</button> </body> </html> |