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) = my style

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

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

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:

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

Output (Before Click):-

Output (After Click):-