×
Community Blog Learn How to Manage Nodes in the DOM

Learn How to Manage Nodes in the DOM

In this blog post, you will learn how you can add, change, replace and remove nodes in the DOM.

By Alex Muchiri.

In previous blog posts, we have already explored how you can access DOM elements and handle the DOM, so from what we have learned so far, we can proceed to use classes, tags, ids, and selectors to look for nodes in the DOM. We can also further use the properties of parents, children, and siblings to find relative nodes in the DOM.

In this part of my tutorial series, you will learn how you can add, change, replace, and remove nodes in the DOM. We will be creating simple JavaScript projects where we can create, modify, and remove elements in the DOM. Our simple programs will be tailored towards the type of changes that are executed on the DOM.

If you work as a front-end developer, then you'll know that the DOM manipulation is routine business. While HTML is the default method, using JavaScript provides a greater level of flexibility and a larger number of features.

The Methods You Can Use with the DOM

In this tutorial, we will be looking at the methods outlined in the table below:

createElement()
appendChild()
removeChild()
replaceChild()
addEventListner()
removeEventListner()
cloneNode()
insertBefore()
setAttribute()
getAttribute()
removeAttribute()

1. createElement()

By using the createElement() method, we can add a new HTML element using some tag such as 'p' by running a simple function. The new element can then be added to the DOM using a method such as AppendChild(), which will be discussed in the next section. The syntax to create new elements is as follows:

document.createElement(tagName);

The parameter in the barckets is the HTML tag that you wish to create. See the code example below, which adds a new paragraph when the button function is executed:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to create a new paragraph text.</p>

<button onclick="myExample()">Button</button>

<script>
function myExample() {
  var myText = document.createElement("P");
  myText.innerText = "This is a new paragraph.";
  document.body.appendChild(myText);
}
</script>

</body>
</html>

Try running this in your browser to see how it works.

2. appendChild()

When the appendChild() method is invoked, a new element is added as the last child of the working HTML element. The method can append a new child altogether, or move an existing child from its current location to the last child position. Here is how the syntax goes:

myElement.appendChild(child)

The parameters for the syntax are the working HTML element (myElement) on which we append the child, and the child element (child) to be appended. See the code example below to see this in action:

<html>
<body>

<p>Click the button add some new text in a paragraph below the button.</p>

<button onclick="myExample()">Button</button>

<script>
function myExample() {
  var para = document.createElement("P");
  var text = document.createTextNode("This is an example.");
  para.appendChild(text);
  document.body.appendChild(para);
}
</script>

</body>
</html>

As can be seen from running the example above, the appendChild() method adds a last child element to the selected parent element. We can rerun the function to add unlimited last child elements.

3. removeChild()

We use the removeChild() method to remove the selected child from the HTML element> it's a simple syntax as shown:

myElement.removeChild(child)

Now, myElement is the parent element of child. Consider an example in the code below:

<html>
<body>

<ul id="myItems"><li>Computer</li><li>Phone</li><li>Camera</li><li>Car</li></ul>

<p>Click the button below to remove the first child from the list if any is available. (index 0).</p>

<button onclick="myExample()">Button</button>

<script>
function myExample() {
  var x = document.getElementById("myItems");
  
  if (x.hasChildNodes()) {
    x.removeChild(x.childNodes[0]);
  }
}
</script>

</body>
</html>

4. replaceChild()

If you want to replace a child element with another one, then the replaceChild() method can come in very handy. The syntax is as shown below:

myElement.replaceChild(newChild, oldChild)

What you need in the argument is the parent element (myElement), and the old and new child (newChild, oldChild). Consider the example below:

<!DOCTYPE html> 
<html> 

    <body> 

        <p>Click on the button below to replace the first item on the list with a new item "My code"</p> 
        <ul id = "listed"><li>My cars</li> 
            <li>My computer</li> 
            <li>My textbook</li> 
        </ul> 
        
        <button onclick ="Example()"> 
            Button
        </button> 
    
        <script> 
        function Example() { 
            var text = document.createTextNode("My code"); 
            var item = document.getElementById("listed").childNodes[0]; 
            item.replaceChild(text, item.childNodes[0]); 
        } 
        </script> 
    
    </body> 
</html>    

5. addEventListener()

An Event describes what happens to an HTML element, which can be anything from a mouse click to being focussed on, as well as mouseover or mouse out. JavaScript enables us to react to such Events if we opt to listen to these events. We can them execute some function if these events happen. The syntax is as follows:

myElement.addEventListener(event, listener, [choices]);

The parameters described include the specified HTML element (myElement), the targeted event (event), and the listening JS function (listener). Choices define the action to take if event has been registered.

<!DOCTYPE html> 
<html> 
<body> 
    <p id="Para">Add a new click event using the button below. Move mouse over the button to register event.</p> 
    <button id="clic">Button </button> 
        <p id="Para"></p> 
    <b id="effect"></b> 
    <script> 
        const a = document.getElementById("clic"); 
        const b = document.getElementById("Para"); 
        a.addEventListener("click", RespondClick); 
        b.addEventListener("mouseover", RespondMouseOver); 
        function RespondMouseOver() { 
            document.getElementById("effect").innerHTML += 
                    "Mouse Event Registered" + "<br>"; 
        } 
        function RespondClick() { 
            document.getElementById("effect").innerHTML += 
                    "Click Registered" + "<br>"; 
        } 
    </script> 
</body> 
</html>

6. removeEventListener()

The removeEventListener() method removes events that have been added using the addEventListener() method. The syntax is quite similar to the one shown above for addEventListener():

myElement.removeEventListener(event, listener, [choices]);

Consider code example below where we modified the addEventListener() method:

<!DOCTYPE html> 
<html> 
<body> 
    <p id="Para">Remove mouseover event using the button below. Move mouse over the button to register event.</p> 
    <button id="clic">Button </button> 
        <p id="Para"></p> 
    <b id="effect"></b> 
    <script> 
        const a = document.getElementById("clic"); 
        const b = document.getElementById("Para"); 
        a.addEventListener("click", RespondClick); 
        b.addEventListener("mouseover", RespondMouseOver); 
        function RespondMouseOver() { 
            document.getElementById("effect").innerHTML += 
                    "Mouse Event Registered" + "<br>"; 
        } 
        function RespondClick() { 
            b.removeEventListener("mouseover", RespondMouseOver); 
            document.getElementById("effect").innerHTML += 
                'You have removed the mouseover effect by clicking the button' + "<br>";
        } 
    </script> 
</body> 
</html>

7. cloneNode()

With the cloneNode() method, new elements are created but they are exact replicas of existing elements on the document. The syntax is as follows:

var replica = myElement.cloneNode([deep])

In the syntax, replica represents a duplicate of myElement, which is the HTML element to replicate. The deep parameter is simply a Boolean value whereby the replicated element carries all child elements of the duplicated HTML element if the flag is true and without them if set to false.

<html>
<body>

<ul id="myItems"><li>Computer</li><li>Phone</li><li>Camera</li><li>Car</li></ul>

<p>Click the button below to clone a child from the available list (child of index 0).</p>

<button onclick="myExample()">Button</button>

<script>
function myExample() {
  var x = document.getElementById("myItems").firstChild;
  
  var duplicate = x.cloneNode(true);
  document.getElementById("myItems").appendChild(duplicate);
}
</script>

</body>
</html>

The function appends the first child to the list when we click on the button.

8. insertBefore()

With the insertBefore() method, we can call a child element using their parent element and insert it before another child element. The syntax is as shown:

myElement.insertBefore(newChild, refChild);

The syntax parameters are the parent element (myElement) , the child to insert (newChild) and the reference child (refChild) on the parent. If the referenced child is non-existent or a null value is passed, the new child will be appended as the last child of the parent element. See code below for example:

<html>
<body>

<ul id="myItems"><li>Peugeot</li><li>Bently</li><li>Ford</li></ul>
<ul id="otherItems"><li>Computer</li><li>Camera</li><li>Car</li></ul>

<p>Click the button below to move items between lists.</p>

<button onclick="myExample()">Button</button>

<script>
function myExample() {
  var x = document.getElementById("otherItems").firstChild;
  var y = document.getElementById("myItems");
  y.insertBefore(x, y.childNodes[0]);
}
</script>

</body>
</html>                     

9. setAttribute()

The setAttribute() method updates the attribute value of an HTML element with a new attribute or simply a new value. The syntax is as shown:

myElement.setAttribute(attName, attValue);

The parameters of the method include the HTML element (myElement), the name (attName) and values (attValue) of the attribute. See the example below:

<!DOCTYPE HTML> 
<html> 
    <body style = "text-align:left;">     
        <p> 
            Input some text in the input field below. 
        </p> 
        
        <form> 
            Input : <input id = "Input" type="text"
                    name="input_field" /> 
        </form> 
        <br> 
                <p> 
            Click on button to make input field read-only. 
        </p> 
        <button onclick = "myExample()"> 
            Button
        </button> 
        
        <p id = "Response" style = 
            "color: red; font-size: 17.5px;"> 
        </p> 
        
        <script> 
            function myExample() { 
                document.getElementById('Input').setAttribute('readonly', true); 
                
                document.getElementById("Response").innerHTML 
                        = "Read-Only attribute enabled"; 
            } 
        </script> 
    </body> 
</html>                    

10. getAttribute()

Calling the getAttribute() method returns an attribute value for a specified HTML element. Below is the syntax:

myElement.getAttribute(attName);

The required parameters include the element (myElement) and the attribute name (attName). Consider this in action in the code example below:

<!DOCTYPE html> 
<html> 
    <body> 
        <left> 
                <p> 
            Click the button below to see some magic!. 
        </p> 
        <br> 
        <button id = "button" onclick = "Howdy()"> 
            Submit 
        </button> 
        <p id="1"></p> 
        <script> 
        function Howdy() { 
        var huloo = 
        document.getElementById("button").getAttribute("onClick"); 
        document.getElementById("1").innerHTML = huloo;             
        } 
        </script> 
    </left> 
    </body> 
</html>

11. removeAttribute()

This method removes an attribute from a specified HTML element. The syntax is as follows:

myElement.removeAttribute(attName);

The required parameters include the element (myElement) and the attribute name (attName). See code example below:

<!DOCTYPE html> 
<html> 
<head> 
    <title>This is an example</title> 
    <style> 
        .voom { 
            color: blue; font-size: 25px; 
        } 
    </style> 
</head> 

<body style="text-align: center;"> 

    <p id="para" class="voom"> 
    How to remove an attribute from DOM document. 
    </p> 

    <button onclick="ATT()"> 
    Remove! 
    </button> 

    <script> 
        function ATT() { 
            <!-- Remove class attributes from 'para' element. -->
            document.getElementById( 
            "para").removeAttribute("class"); 
        } 
    </script> 
</body> 
</html>

Conclusion

In this blog post, we have looked through the various methods of using JavaScript to create new nodes and element, including inserting, replacing, and modifying nodes.

Do you have an Alibaba Cloud account? Sign up for an account and try over 40 products for free. This deal is worth up to $1300. Get Started with Alibaba Cloud to learn more.

The views expressed herein are for reference only and don't necessarily represent the official views of Alibaba Cloud.

0 1 0
Share on

Alibaba Clouder

2,599 posts | 762 followers

You may also like

Comments