DOM CSS

The HTML DOM allows a user with the help of JavaScript to change or modify the style of HTML elements.


Changing/Modifying HTML Style

To modify the style of an HTML element, use the below syntax:

document.getElementById(id).style.property = my style

The following example changes the style of a <span> element:

Input:-
<html>
   <body>
      <span id="id1">Hello World!</span>
      <script>
         document.getElementById("id1").style.color = "red";
      </script>
      <p>The span color was changed by a script.</p>
   </body>
</html>

Output :-


Using Events

The HTML DOM allows user to execute dynamic code when an event occurs or happens.

Events are generated by the browser when “things happen or some action taken” to HTML elements. Eg:-

  • An element is clicked
  • Page has loaded
  • Change in value of Input fields

The below example changes the style of the HTML element with id="h3", when the user clicks a button:

Input:-
<!DOCTYPE html>
<html>
   <body>
      <h3 id="h3">My H3</h3>
      <button type="button" 
         onclick="document.getElementById('h3').style.color = 'red'">
      Click Here!</button>
   </body>
</html>

Output (Before Click):-

Output (After Click):-