Mastering JavaScript DOM Manipulation: A Guide to Inserting, Replacing, and Removing Child Elements

In this tutorial, we'll explore techniques for DOM Manipulation, focusing on inserting, replacing, and removing child elements using JavaScript. This guide is designed to assist students, beginners, or those new to JavaScript programming, providing a valuable reference for enhancing their knowledge and skills in developing effective web applications. Throughout the tutorial, I'll provide explanations and JavaScript snippets demonstrating the usage of each method.

Understanding DOM Manipulation

DOM Manipulation entails the dynamic interaction and modification of the structure, content, and style of a web document, be it HTML, XML, or XHTML. This process is achieved through programming languages like JavaScript.

How to Insert, Replace, and Remove Child Element in JavaScript?

JavaScript comes with some useful functions and methods that was primarily crafted for manipulating the DOMs. One of the methods is knwon as `append()`, primarily developed to add or append a new node element in a specific parent element. The new child element will be added after the last item of the child elements.

When it comes to replacing an existing child element, JavaScript introduces a handy method called `replaceWith()`. This method plays a crucial role in achieving the functionality of replacing the current child element or any existing element within the document with a new one.

Finally, JavaScript provides a valuable function known as `remove()`. This function is designed to efficiently remove or delete the selected DOM element.

How to Implement these Methods:

Below are sample snippets illustrating the application of the `append()`, `replaceWith()`, and `remove()` methods:

Utilizing the `append` method

The `append()` method is a powerful tool for a node or DOM element, requiring another node as an argument that will be added to the current element. See the example below.

  1. const RandomList = document.getElementById('random-list')
  2.  
  3. const listItem = document.createElement('li')
  4.  
  5. var content = `Sample Content`;
  6. var row = document.createElement('div')
  7. row.innerHTML = `<div>${content}</div>`
  8. listItem.innerHTML = row.outerHTML
  9.  
  10. RandomList.appendChild(listItem)

Applying the `replaceWith()` method

The `replaceWith()` method, belonging to the Node or DOM element, swaps the existing element with a new one. It mandates the presence of the new Node or DOM element as an argument.

  1. const RandomList = document.getElementById('random-list')
  2.  
  3. const listItem = document.createElement('li')
  4.  
  5. var content = `Sample Content`;
  6. var row = document.createElement('div')
  7. row.innerHTML = `<div>${content}</div>`
  8. listItem.innerHTML = row.outerHTML
  9.  
  10. var items = RandomList.querySelectorAll('.list-group-item')
  11. var old_item = items[0]
  12.  
  13. old_item.replaceWith(listItem)

Employing the `remove()` method

The `remove()` method, associated with a node element, eradicates the current node from the document.

  1. const RandomList = document.getElementById('random-list')
  2. var items = RandomList.querySelectorAll('.list-group-item')
  3. var old_item = items[0]
  4.  
  5. old_item.remove(old_item)

I've developed a straightforward web application utilizing HTML, CSS, and JavaScript to showcase the practical application of the append(), replaceWith(), and remove() methods within an authentic webpage.

The uncomplicated application includes a single list container, an insert button, a replace input and button, and a remove or delete button. Below is the entire source code for this straightforward web application page.

CSS

This script serves as a CSS file defining custom styles for various elements on the web page. It is identified as `style.css`.

  1. @import url('https://fonts.googleapis.com/css2?family=Ubuntu+Mono:ital,wght@0,400;0,700;1,400;1,700&display=swap');
  2. * {
  3. font-family: 'Ubuntu Mono', monospace;
  4. }
  5. html, body{
  6. height: 100%;
  7. width: 100%;
  8. max-height: 100%;
  9. overflow: auto;
  10. }
  11.  
  12. body{
  13. background-color:#c2e9fb ;
  14. background-image: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);
  15. }
  16.  
  17. #page-title{
  18. color:#fff;
  19. text-align: center;
  20. font-size: 1.8rem;
  21. letter-spacing: .3px;
  22. font-weight: 700;
  23. text-shadow: 0px 3px 5px #22222252;
  24. }
  25. #random-list{
  26. position: relative;
  27. counter-reset: item;
  28. }
  29. #random-list>li:before{
  30. counter-increment: item;
  31. content: counter(item) ".";
  32. position: absolute;
  33. height: 100%;
  34. width: 50px;
  35. left: 15px;
  36. }
  37. #random-list:empty{
  38. display: flex;
  39. width: 100%;
  40. justify-content: center;
  41. }
  42. #random-list:empty::before{
  43. content: "No item listed yet.";
  44. text-align: center;
  45. width: 100%;
  46. padding: .5em;
  47. font-style: italic;
  48. color: #c3c3c3;
  49. }
  50. button.rem-item {
  51. display: flex;
  52. align-items: center;
  53. justify-content: center;
  54. font-size: 17px;
  55. height: 30px;
  56. }

HTML

This script represents an HTML file encompassing essential elements of the web page. The file is labeled as `index.html`.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  5. <title>JavaScript Tutorial</title>
  6. <!-- Fontawesome CSS -->
  7. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  8. <!-- Custom CSS -->
  9. <link rel="stylesheet" href="style.css">
  10. <!-- Bootstrap jQuery -->
  11. <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
  12. <!-- Bootstrap JS -->
  13. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  14. </head>
  15. <div class="container-md py-5">
  16. <!-- Page Title -->
  17. <div id="page-title" class="mb-3">Insert, Replace, and Remove Child Element using JavaScript</div>
  18. <div class="d-flex justify-content-center w-100">
  19. <hr class="border-3 border-dark bg-opacity-100 shadow" style="width:50px">
  20. </div>
  21. <!-- Page Title -->
  22. <div class="row justify-content-center">
  23. <div class="col-lg-6 col-md-10 col-sm-12 col-12">
  24. <div class="card rounded-0 shadow">
  25. <div class="card-header rounded-0">
  26. <div class="card-title">Random List Items</div>
  27. </div>
  28. <div class="card-body">
  29. <div class="container-fluid">
  30. <!-- List Container -->
  31. <div id="random-list" class="list-group mb-3"></div>
  32. <!-- List Container -->
  33. <div class="text-center"><small class="text-body-emphasis fw-bold">Actions:</small></div>
  34. <!-- Actions Container -->
  35. <div class="list-group">
  36. <div class="list-group-item d-flex w-100 justify-content-center align-items-center">
  37. <div class="col-lg-6 col-md-8 col-sm-12 col-12">
  38. <!-- Button for Item Insertion -->
  39. <button class="btn btn-sm btn-primary rounded-pill w-100" id="add_item" type="button">Add Item</button>
  40. </div>
  41. </div>
  42. <div class="list-group-item d-flex w-100 justify-content-center align-items-center">
  43. <div class="input-group">
  44. <!-- Input for Item to Replace -->
  45. <input type="number" id="replace-item-inp" min="1" class="form-control form-control-sm" placeholder="" aria-describedby="replace-item">
  46. <!-- Button for replacing the Item -->
  47. <button class="btn btn-m btn-primary" type="button" id="replace-item">Replace</button>
  48. </div>
  49. </div>
  50. </div>
  51. <!-- Actions Container -->
  52. </div>
  53. </div>
  54. </div>
  55. </div>
  56. </div>
  57. </div>
  58. </body>
  59. <script src="script.js"></script>
  60. </html>

JavaScript

Finally, the following script is the JS file containing the code that enables the functional features of the web page. This file is referred to as `script.js`.

  1. // Random List Element (Parent Element)
  2. const RandomList = document.getElementById('random-list')
  3. // Button/Element that triggers to add Item into the list when clicked
  4. const actionBTN = document.getElementById('add_item')
  5. // Button/Element that triggers to replace Specific Item from the list with a new Item when clicked
  6. const ReplaceBTN = document.getElementById('replace-item')
  7.  
  8. // Sample List Item possible contents
  9. const textData = [
  10. "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
  11. "Proin posuere molestie tellus vitae blandit.",
  12. "Nullam vitae metus a justo venenatis finibus in nec ante.",
  13. "Nam nec pellentesque velit.",
  14. "Nullam sodales suscipit lacus accumsan dapibus.",
  15. "Integer interdum est mollis purus malesuada convallis.",
  16. "Aliquam gravida ante sit amet imperdiet ornare.",
  17. "Proin tincidunt neque nec rhoncus pretium.",
  18. "Maecenas tristique maximus eleifend."
  19. ];
  20.  
  21. // Item to Insert as New Child Element
  22. const listItem = document.createElement('li')
  23. listItem.classList.add("list-group-item", "list-group-item-action", "ps-5")
  24.  
  25. // Function that generates the new List Item
  26. function create_new_el(){
  27. var item = listItem.cloneNode();
  28. var content = textData[Math.floor( Math.random() * textData.length)];
  29. var row = document.createElement('div')
  30. row.classList.add("row", "justify-content-between")
  31. row.innerHTML = `<div class="col-10">${content}</div>`
  32. row.innerHTML += `<div class="col-auto"><button type="button" class="rem-item btn btn-sm btn-outline-danger">&times;</div>`
  33. item.innerHTML = row.outerHTML
  34. return item;
  35. }
  36.  
  37. // Event Listener that insert new Item into the list when add button triggered
  38. actionBTN.addEventListener('click', function(e){
  39. e.preventDefault()
  40. // Generate New Item
  41. var item = create_new_el();
  42. // Append or add the new Item after the last item on the list
  43. RandomList.appendChild(item)
  44.  
  45. // Event Listener for Removing or Deleting the Child Element From the List
  46. item.querySelector('.rem-item').addEventListener('click', function(e){
  47. e.preventDefault()
  48. item.remove()
  49. })
  50. })
  51.  
  52. // Event Listener for replacing the existing Child Element
  53. ReplaceBTN.addEventListener('click', function(e){
  54. e.preventDefault()
  55. // Get the Selected List Item to replace with
  56. var itemNo = document.getElementById('replace-item-inp').value
  57.  
  58. // Index of the Child Element to replace
  59. var index = parseInt(itemNo) - 1;
  60. // Listing All the List Items
  61. var items = RandomList.querySelectorAll('.list-group-item')
  62. // Selecting the list item to replace
  63. var old_item = items[index]
  64.  
  65. // Validate if the provided List Item Number is valid and the child Item exists
  66. if(parseInt(itemNo) < 1 || old_item == undefined){
  67. alert("Please Provide Valid List Item #");
  68. return false;
  69. }
  70. // Generate New Item
  71. var item = create_new_el()
  72.  
  73. // Replacing the the item
  74. old_item.replaceWith(item)
  75. })

Snapshot

Here is the snapshot displaying the outcome of the provided scripts:

A Guide to Inserting, Replacing, and Removing Child Elements in JS

There you have it! I've also supplied the zip file containing the comprehensive source code of the web application I crafted on this website. Feel free to download and customize it according to your preferences.

I hope that this Guide to Inserting, Replacing, and Removing Child Elements using JavaScript will be valuable for your current and future web application projects. Explore further on this website for additional Free Source Codes, Tutorials, and Articles covering various programming languages.

Happy Coding =)

Add new comment