Changing the CSS Property of an HTML Element in the JavaScript DOM

Introduction to DOM Manipulation

Manipulating the DOM is key to creating interactive web pages. JavaScript allows you to change the style of HTML elements on the fly without refreshing the page.

A Practical Example: Changing a Div’s Background Color

Let’s add a button and a div to our index.ejs file, and then use JavaScript to change the div’s background color when the button is clicked.

HTML Structure

Update your index.ejs to include the following HTML elements:

<body>
  <h1><%= message %></h1>
  <p>Welcome to your EJS templated page!</p>
  <img src="/example.jpg" alt="Example Image" class="responsive-img">

  <!-- Div that will change color -->
  <div id="colorBox" style="width: 200px; height: 200px; background-color: lightblue; margin-top: 20px;">
    Click the button to change my color!
  </div>

  <!-- Button to trigger the color change -->
  <button id="changeColorBtn" style="margin-top: 20px;">Change Color</button>

  <!-- JavaScript to manipulate the DOM -->
  <script>
    // Wait until the DOM is fully loaded
    document.addEventListener('DOMContentLoaded', function() {
      // Select the button and div elements
      const button = document.getElementById('changeColorBtn');
      const box = document.getElementById('colorBox');

      // Add a click event listener to the button
      button.addEventListener('click', function() {
        // Change the CSS property 'background-color'
        box.style.backgroundColor = box.style.backgroundColor === 'lightblue' ? 'salmon' : 'lightblue';
      });
    });
  </script>
</body>

Explanation

  • HTML Elements: We added a <div> with an initial background color and a <button> to trigger the color change.
  • JavaScript DOM Manipulation:
    • We use document.getElementById to select both the button and the div.
    • An event listener is added to the button, so when it’s clicked, the background color of the div toggles between lightblue and salmon.
    • The inline style of the div is directly modified using element.style.backgroundColor.

This simple example demonstrates how to interact with and modify the DOM dynamically.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top