Open In App

How to work with document.documentElement in JavaScript?

Last Updated : 18 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, document.documentElement is a fundamental property that refers to the root element of an HTML document. This property provides a way to access and manipulate the entire HTML document structure. In this tutorial, we will focus on how to work with document.documentElement in JavaScript.

Preview

Screenshot-_337_

Output

Approach

  • At first create a basic html structure with some css style as your needs.
  • In the javascript part use document.documentElement to access the root element of the HTML document.
  • Then get a reference of the button using document.getElementById() or any other method.
  • Add an event listener to the button to handle the click event.
  • Define a function to handle changing the background color of the root element when the button is clicked.
  • You can define a function to handle clicks attached to the root element. This function can then check if the root element itself was clicked and display an alert if necessary.

Example: To demonstrate clicking the button handling the click event attached to it using JavaScript.

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Document Root Element Example</title>
    <style>
        .main-container{
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            margin-top: 10rem;
        }
        #changeColorButton{
            padding: 10px 20px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
    
</head>
<body>
<div class="main-container">
    <h1>Welcome to Document Root Element Example</h1>
    <p>Click the button to change the background
       color of the HTML root element.</p>
    <button id="changeColorButton">Change
        Background Color</button>
</div>


<script>
    // Accessing the root element
    let rootElement = document.documentElement;
    let changeColorButton = document
                           .getElementById("changeColorButton");

    function changeBackgroundColor() {
        rootElement.style.backgroundColor = "lightblue";
    }
    
    changeColorButton.addEventListener("click",
                      changeBackgroundColor);

    // Function to handle root element click
    function handleRootElementClick() {
        alert("Root element clicked!");
    }

    // Adding event listener to the root element
    rootElement.addEventListener("click",
                handleRootElementClick);
</script>

</body>
</html>

Output:

peek1


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads