Clear and Replace Children of Element with Javascript


In web applications development, some HTML elements can contain one or more child elements. Using javascript, the children of HTML element can be modified to suit the current view or application data. Sometimes, it becomes necessary to clear the entire children of an HTML parent element, and or replace them with a different set of child elements.

In this post, we will learn to know how we can clear children of a parent object, and how we can also replace them with a different set of child elements. We will consider different methods that can be used to accomplish this task.

To have a better understanding, we will also take a practical approach, with example, to demonstrate what we discuss in this post. We will first explain the methods that can be used to clear and replace children of a parent object, and then look at a working example that demonstrates how we can accomplish this task.

Clear Children with replaceChildren()

The simplest approach to clear children of a parent element is to call replaceChildren() method of the parent object without supplying any values to the method call. replaceChildren() accepts an infinite number of Node and string objects which can be provided to the method to replace the existing child elements. If we do not provide any values to replaceChildren() in its call, then it will simply clear the existing list of child items for the calling parent object.

Suppose we have the following HTML extract:

HTML
<ul id="list">
    <li>HTML</li>
    <li>CSS</li>
    <li>Javascript</li>
</ul>

We can clear all li items with replaceChildren() when we have a reference to the parent ul element:

JavaScript
// get the ul element
const ul = document.getElementById('list');

// To clear all items, don't provide any replacement nodes
ul.replaceChildren();

Since no Node or string objects are supplied to replaceChildren() method, there will be no items to replace the cleared ones. The effect is that replaceChildren(), without any argument values provided, will clear the entire set of child elements of the parent object without replacement.

Clear Children with removeChild()

An alternative method to clear children of a parent object is to call removeChild() method for each child element. This approach works by iterating through the children of the parent object, and removing each child element one at a time in the iteration. We can use a while loop condition to check if the parent object contains some child objects. This is done with a call to hasChildNodes(). If a child item exists, then we call removeChild() by passing to it either the firstChild or lastChild property of the parent object.

JavaScript
// get the ul element
const ul = document.getElementById('list');

// check to see if child items exist, if so call to remove each child that exists
while (ul.hasChildNodes())
    ul.removeChild(ul.firstChild);

The while loop condition tests if the parent element contains some child items. As long as a child exists, hasChildNodes() will return true, and the first child item will be removed. When all child items have been removed, hasChildNodes() will return false, and the while loop will terminate.

If we want to remove the items from the bottom, we can pass lastChild property of the parent object to removeChild(). The result will be the same. All child items will be removed from the parent object.

JavaScript
// check to see child items exist, if so call to remove each child that exists
while (ul.hasChildNodes())
    ul.removeChild(ul.lastChild);

From line 3, we pass lastChild property of the parent object, which is ul, to removeChild() to remove child items from the bottom.

Replace Children with replaceChildren()

To replace children of an element with new set of child elements, we will need to call replaceChildren() method and provide it with an unlimited number of child items that will replace the existing ones.

Suppose in listing 1, we want to replace all li items with new ones. The following javascript code demonstrates how we can call replaceChildren() with new child items for replacement.

JavaScript
// create list items
const li1 = document.createElement('li');
const li2 = document.createElement('li');
const li3 = document.createElement('li');

// set text for each list item
li1.innerText = 'PHP';
li2.innerText = 'Javascript';
li3.innerText = 'Python';

// get the ul element
const ul = document.getElementById('list');

// replace with new list items
ul.replaceChildren(li1, li2, li3);

Like appendChild(), replaceChildren() also accepts unlimited Node and string objects as arguments. Hence, we can also pass string objects as argument to replaceChildren() method call.

JavaScript
// replace with new list items
ul.replaceChildren(li1, li2, li3, 'Laravel');

Observe that the last item passed to replaceChildren() in the previous code is a string object. As indicated earlier, replaceChildren() accepts both Node and string objects as argument. Additionally, there is no limit to the number of items that can be passed to it.

With our current understanding of how to clear children and replace children of a parent object, we can take a practial example to broaden our understanding of the discussions so far.

Practical Example

In this practical example to clear and replace children of a parent object, we will randomly generate some integer values as list items. We will introduce two buttons: one to clear the child items without replacement, and another to replace the child items. We will do this dynamically with javascript.

Create HTML document file and give it any name of your chossing, such as index.html. Also, create a javascript file in which we will define our javascript functions. You can give it any name, for example index.js.

Copy and paste the following content into index.html file. You should notice that we are also loading the javascript file that was created, in my case index.js, on line 24.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clear and Replace Element Children</title>
</head>
<body>
    <div class="container">
        <ul id="list">
            <li>34</li>
            <li>28</li>
            <li>46</li>
            <li>17</li>
        </ul>

        <hr />
        <div class="controls">
            <button onclick="clearChildren()">Clear</button>
        </div>
    </div>

    <!-- load the javascript file -->
    <script type="text/javascript" src="./index.js"></script>
</body>
</html>

The content of the HTML is very clear. We are rendering an unsorted list of some random numbers. We can identify that the onclick event of the button is set to clearChildren(). We will define this function in the javascript file shortly. When the button is clicked, clearChildren() will be called to clear all child items of the ul element.

If you preview the HTML document file in a web browser, you should see a page similar to the following:

Let’s see how we can separately clear and replace list items of the parent object.

Clear Children of Parent Element

In listing 7, we have set the onclick event of the button for clearing the list items to clearChildren(). Let’s define this function in the javascript file. We will call replaceChildren() in the function definition to clear all the list items of the ul element. Remember that a call to replaceChildren() method without any arguments will clear the existing child items with any replacement.

JavaScript
// get reference to the ul element
const ul = document.getElementById('list');

function clearChildren() {
    // clear the list items with no replacement
    ul.replaceChildren();
}

With clearChildren() defined in the javascript file, go ahead and click on the Clear button. You will notice that the list of numbers will disappear. You can see the result below:

clear children

The call to replaceChildren() cleared all the child items of the ul element. Since we did not provide any values to replaceChildren(), no new list items were used to replace the ones that were cleared.

To keep on playing with it, refresh the page to have the initial page rendered. You can then continue to click on the Clear button to see it working.

Replace Children of Parent Element

To see how we can replace children of a parent object with new items, we will introduce a new button element. We will label this button as Replace. When this button is clicked, we will generate random numbers from 10 to 50 which we will use to create Element objects of li to replace the existing child items.

Within <div class="controls"></div>, update the HTML to include the new button element for replacement:

HTML
...

<div class="controls">
    <button onclick="clearChildren()">Clear</div>
    <button onclick="replaceChildren()">Replace</div>
</div>

You can see the introduction of the new button at line 5. We have set the onclick event of this new button to replaceChildren(). This replaceChildren() does not yet exist in the javascript file. We will define it shortly.

replace children button

In addition to replaceChildren() function, we will also need another function that will create li items of random integer numbers.

In the javascript file, add two more functions as replaceChildren() and getRandomItems() with their implementations as shown below:

JavaScript
...

// function to replace list items with new ones
function replaceChildren() {
    // get the random list items
    const randomList = generateRandomItems();

    // replace with the new items
    ul.replaceChildren(...randomList);
}

// function to create li items of random numbers
function getRandomItems() {
    const count = 4, min = 10, max = 50;
    const items = [];

    for (let i = 0; i < count; i++) {
        let li = document.createElement('li');
        li.innerText = Math.floor(Math.random() * (max - min) + min);

        items[i] = li;
    }

    // return the generated list items
    return items;
}

Our main interest is in replaceChildren() function. As can be seen, a call to getRandomItems() is made to generate and return an array of randomly generated li items. Since an array is iterable, we are able to pass the returned value, in this case randomList, to replaceChildren() method of the ul element using the spread syntax.

Any time the Replace button is clicked, you will notice that the list of numbers rendered on the page are replaced with a new set of numbers. This is done with the call to replaceChildren() on line 9 where we pass that list items using the spread syntax. The following image shows the result of clicking on the Replace button. Understand that the values will not necessarily be the same as yours since they are randomly generated.

replace children

Thus, to replace children of a parent object, we need to call replaceChildren() method of that parent object and provide it with a new set of values for replacement. Continue clicking on the Replace button to see that the list gets replaced with a new set of integer values.

Summary

In this post, we have seen how we can clear children of a parent object as well as how to replace children of a parent object.

To clear children of a parent object, we need to call replaceChildren() method of the parent object without passing any values to the method call. replaceChildren() will clear the existing child items when called.

JavaScript
// get reference to the ul element
const ul = document.getElementById('list');

// To clear all items, don't provide any replacement nodes
ul.replaceChildren();

Since no new values are provided to the method when called, there will be no new set of values to be used for replacement.

Another approach to clear children of a parent object is to remove the child items one at a time with removeChild() method of that parent object. Using a while loop, we can check if any child exists. If a child exists, we can pass either firstChild or lastChild properties to removeChild() method of the parent object.

JavaScript
// get reference to the ul element
const ul = document.getElementById('list');

while (ul.hasChildNodes())
    ul.removeChild(ul.firstChild);

If we want to replace child elements of a parent object with new items, we need to call replaceChildren() method and provide it with the new set of items that will be used to replace the existing child items:

JavaScript
// get the ul element
const ul = document.getElementById('list');

// replace with new list items
ul.replaceChildren(li1, li2, li3);

Leave a Reply

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