Inserting New Element Before or After Existing Element using Pure JavaScript Tutorial

In this tutorial, you can learn how to Insert a New Element Before or After existing elements using JavaScript. The main purpose of this tutorial is to provide students and beginners with a reference for learning some techniques and usage using the JavaScript built-in methods. Here, I will be providing a sample web application that demonstrates the usage of JavaScript insertBefore and after methods.

How to Insert New Element Before and After existing Element?

JavaScript comes with useful built-in methods and APIs including the insertBefore and after method. These methods are very handy in manipulating the Page Interface or DOM. The insertBefore method helps the developer to insert an element inside the parent element and before the specific child element. The after method can help us to insert an element after the existing element. Check out the following syntax for the usage of the given JS method.

insertBefore() Syntax

The below snippet is a sample usage of the JS insertBefore method.

  1. //Parent Element Wrapper
  2. const parentEl = document.getElementId('parent')
  3. //Child Element
  4. const childEl = document.getElementId('child1')
  5. // New Element
  6. const newEl = document.createElement('div')
  7. newEl.innerHTML = `<p>Sample Content</p>`
  8.  
  9. // Insert New Element Before the Child Element
  10. parentEl.insertBefore(newEl, childEl)

after() Syntax

The below snippet is a sample usage of the JS after method.

  1. //Existing Element
  2. const existingEl = document.getElementId('sampleEl')
  3. // New Element
  4. const newEl = document.createElement('div')
  5. newEl.innerHTML = `<p>Sample Content</p>`
  6.  
  7. // Insert New Element After the Existing Element
  8. existingEl.after(newEl)

Sample Web Application

Here, I will be providing a simple web page that demonstrates the usage of the insertBefore() and after() methods. The scripts below will result in a simple web page that contains a simple list view with items that allow the user to clone it and insert the cloned items with updated text content before or after the selected element.

Page Interface

Here is the HTML file script. The file is known as index.html.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>JS - Insert Element Before or After an Element</title>
  7. <link rel="preconnect" href="https://fonts.googleapis.com">
  8. <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  9. <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
  10. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  11. <link rel="stylesheet" href="style.css">
  12. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  13. </head>
  14. <div class="content-md-lg py-3">
  15. <div class="page-title">Inserting Element Before or Afrer an Element using JavaScript</div>
  16. <hr style="margin:auto; width:25px" class="border-light opacity-100">
  17. <div class="container-lg">
  18. <div class="row py-3">
  19. <div class="col-lg-5 col-md-5 col-sm-10 col-12 mx-auto">
  20. <div class="card bg-dark rounded-0 border-dark-subtle">
  21. <div class="card-body rounded-0">
  22. <!-- Sample Insertion Wrapper -->
  23. <div class="list-group rounded-0" id="InsertWrapper">
  24. <div class="list-group-item insertedItem">
  25. <div class="d-flex w-100 align-items-center">
  26. <div class="col-auto flex-shrink-1">
  27. <button type="button" class="btn btn-outline-primary btn-sm rounded-0 insertBefore"><span class="material-symbols-outlined">tab_new_right</span></button>
  28. </div>
  29. <div class="col-auto flex-shrink-1 flex-grow-1 text-center textContent"> Sample Element #1</div>
  30. <div class="col-auto flex-shrink-1">
  31. <button type="button" class="btn btn-outline-info btn-sm rounded-0 insertAfter"><span class="material-symbols-outlined">tab_new_right</span></button>
  32. </div>
  33. </div>
  34. </div>
  35. <div class="list-group-item insertedItem">
  36. <div class="d-flex w-100 align-items-center">
  37. <div class="col-auto flex-shrink-1">
  38. <button type="button" class="btn btn-outline-primary btn-sm rounded-0 insertBefore"><span class="material-symbols-outlined">tab_new_right</span></button>
  39. </div>
  40. <div class="col-auto flex-shrink-1 flex-grow-1 text-center"> Sample Element #2</div>
  41. <div class="col-auto flex-shrink-1">
  42. <button type="button" class="btn btn-outline-info btn-sm rounded-0 insertAfter"><span class="material-symbols-outlined">tab_new_right</span></button>
  43. </div>
  44. </div>
  45. </div>
  46. </div>
  47. <!-- Sample Insertion Wrapper -->
  48. </div>
  49. </div>
  50. </div>
  51. </div>
  52. </div>
  53. </div>
  54. <script src="script.js"></script>
  55. </body>
  56. </html>

Stylesheet

Here is the CSS file script. The file is known as style.css.

  1. @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@200&family=Space+Mono&display=swap" rel="stylesheet');
  2. :root{
  3. --space-mono-font: 'Space Mono', monospace;
  4. --border-dark-subtle: #373838;
  5. }
  6. *{
  7. box-sizing: border-box;
  8. }
  9. body *{
  10. font-family: var(--space-mono-font);
  11. }
  12. /**
  13. Page Design
  14. */
  15. body,
  16. html{
  17. height: 100%;
  18. width: 100%;
  19. margin: 0;
  20. padding: 0;
  21. }
  22. body{
  23. background-color: #282A3A;
  24. }
  25. .page-title{
  26. font-size: 2.5rem;
  27. font-weight: 500;
  28. color: #fff;
  29. letter-spacing: 3px;
  30. font-family: var(--secular-font);
  31. text-align: center;
  32. text-shadow: 0px 0px 3px #2020208c;
  33. }
  34. .border-dark-subtle{
  35. border-color: var(--border-dark-subtle) !important;
  36. }
  37.  
  38. /* Button Icons Style*/
  39. .insertBefore > span{
  40. rotate: -90deg;
  41. }
  42. /* Button Icons Style*/
  43. .insertAfter > span{
  44. rotate: 90deg;
  45. }

JavaScript

Here is the JavaScript file script. The file is known as script.css.

  1. // Parent Container Selector
  2. const ParentWrapper = document.getElementById('InsertWrapper')
  3. // Next Element ID
  4. var i = document.querySelectorAll('.insertedItem').length
  5. // Sample Element to Insert
  6. // Here I will just clone the first element and change the content text later on
  7. const InsertEl = ParentWrapper.querySelector('.insertedItem:nth-child(1)').cloneNode(true)
  8.  
  9.  
  10. /**
  11.   * Inserting Element Before an Element
  12.   * @param {DOM Element} el
  13.   * - Target Element to insert the new element before
  14.   */
  15. const InsertElBefore = (el) =>{
  16. // Incrementing Item Iteration #
  17. i++;
  18. // Clone Element as the New Element
  19. var newEl = InsertEl.cloneNode(true)
  20. // Updating the New Elements Text Content
  21. newEl.querySelector('.textContent').innerText = `Sample Element #${i}`;
  22. //Inserting the new Element into the parent wrapper and before the specific child element
  23. ParentWrapper.insertBefore(newEl, el)
  24. //Adding functionality to the New Element buttons
  25. InsertBtnFunc(newEl)
  26. }
  27. /**
  28.   * Inserting Element After an Element
  29.   * @param {DOM Element} el
  30.   * - Target Element to insert the new element after
  31.   */
  32. const InsertElAfter = (el) =>{
  33. // Incrementing Item Iteration #
  34. i++;
  35. // Clone Element as the New Element
  36. var newEl = InsertEl.cloneNode(true)
  37. // Updating the New Elements Text Content
  38. newEl.querySelector('.textContent').innerText = `Sample Element #${i}`;
  39. //Inserting the new Element after the specific element
  40. el.after(newEl)
  41. //Adding functionality to the New Element buttons
  42. InsertBtnFunc(newEl)
  43. }
  44.  
  45. /**
  46.   * Inserted Items buttons Functionality
  47.   * @param {DOM Element} el
  48.   * - Target Element
  49.   */
  50. const InsertBtnFunc = (el)=>{
  51. // Trigger Inserting Before
  52. el.querySelector('.insertBefore').addEventListener('click', e => {
  53. InsertElBefore(el)
  54. })
  55. // Trigger Inserting After
  56. el.querySelector('.insertAfter').addEventListener('click', e => {
  57. InsertElAfter(el)
  58. })
  59. }
  60.  
  61. /** Add the Button Function to the defualt Items */
  62. ParentWrapper.querySelectorAll('.insertedItem').forEach(el => {
  63. InsertBtnFunc(el)
  64. })

Snapshots

Here are the images of the overall result of the script I provided above.

Inserting Before

Element Before or After Existing Element using Pure JavaScript Tutorial

Inserting After

Element Before or After Existing Element using Pure JavaScript Tutorial

Inserting After and Before

Element Before or After Existing Element using Pure JavaScript Tutorial

There you go! I have also provided the source code zip file that I created for this tutorial on this website and it is free to download. Feel free to download it by clicking the download button located after this tutorial's content.

That's it! I hope this Inserting New Element Before or After Existing Element using Pure JavaScript Tutorial will help you with what you are looking for and will be useful for your current and future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Add new comment