Open In App

How to get a notification when an element is added to the page using JavaScript?

Last Updated : 24 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To show a notification when an element is added to the page we can use the to createElement() method to create an element list with the specified name. Detect element addition dynamically in the DOM using JavaScript. Trigger an alert to notify users upon appending new elements to the page.

Approach

  • The JavaScript function add() is defined to handle the process of adding an <li> element to the DOM when invoked by clicking a button.
  • Inside the function, a new <li> element is dynamically created using document.createElement("li").
  • A text node containing the string "JS" is created using document.createTextNode("JS").
  • The text node is appended as a child of the <li> element, and then the <li> element is appended to an existing <ul> list with the id "myList".
  • After the element is appended, an alert message is triggered using an alert("Element is getting added"), notifying the user that an element has been added to the page.

Example: The example below shows the above-explained approach.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>button to append an item
        to the end of the list</title>
</head>

<body>
    <b>
        Click the button to append an item
        to the end of the list.
    </b>
    <ul id="myList">
        <li>HTML</li>
        <li>CSS</li>
    </ul>
    <br>
    <button onclick="add()">
        Add Elements
    </button>
    <script>
        function add() {

            // Add li element 
            let node = document
                .createElement("li");

            // Add element into the list
            let textnode = document
                .createTextNode("JS");

            // Append the element into the list
            node.appendChild(textnode);
            document.getElementById("myList")
                .appendChild(node);

            // Alert message when element gets added
            alert("Element is getting added");
        }
    </script>
</body>

</html>

Output: 

addelementgif

Next Article

Similar Reads