Unable to append DOM element using the node.insertBefore() method

I am facing an issue with a sorted list of items displayed alphabetically. My intention was to insert a corresponding letter from the alphabetArr array after each <li> element, using an id from the DOMElementsArr array. However, I seem to be missing something crucial in my implementation.

Although there are no errors in the console, the functionality is not working as expected.

The arrays in question are as follows:

let alphabetArr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
    "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

let DOMElementsArr = ['8MM', ... ,'Daddy_Day_Care']

This is my current approach:

// Function to insert new element
function insertAfter(el, referenceNode) {
  referenceNode.parentNode.insertBefore(el, referenceNode.nextSibling);
}

// Function to loop through both arrays
function injectAllAlphabetLetters(){

  // Create new element
  let newEl = document.createElement('li');
  newEl.className = 'titles alphabet';

  for (let i = 0; i < alphabetArr.length; i++){
  console.log(alphabetArr[i]);
  newEl.innerHTML = alphabetArr[i][0];
  }

  let ref; 

  for (let j = 0; j < DOMElementsArr.length; j++){
    console.log(DOMElementsArr[j]);
    ref = document.getElementById(DOMElementsArr[j]);
  }

  insertAfter(newEl, ref);
}

injectAllAlphabetLetters();

Answer №1

Your current code is creating a single element, updating its content in a loop, getting the next element in each iteration, and then calling the insertAfter function only once with the last set of values.

To make it work correctly, you need to combine the loop logic with the insertion code within the loop itself.

// Function to insert new element after a reference node
function insertAfter(el, referenceNode) {
  referenceNode.parentNode.insertBefore(el, referenceNode.nextSibling);
}

// Function that iterates through both arrays and injects alphabet letters
function injectAllAlphabetLetters() {
  // Iterate until the end of the shorter array length
  for (let i = 0; i < alphabetArr.length && i < DOMElementsArr.length; i++) {    
    // Create a new element and set properties
    let newEl = document.createElement('li');
    newEl.className = 'titles alphabet';    
    newEl.innerHTML = alphabetArr[i][0];

    // Get the element based on its ID
    let ref = document.getElementById(DOMElementsArr[i]);    
  
    // Call the function to insert the new element after the reference node
    insertAfter(newEl, ref);
  }

}

// Call the main function to inject all alphabet letters
injectAllAlphabetLetters();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Adding a grid panel to the final node of a tree-grid in extjs: A step-by-step guide

Does anyone have a suggestion on how to add a grid panel to the last node/children of a treepanel dynamically? I would like to append the gridpanel dynamically and for reference, I am providing a link: Jsfiddle I also need to ensure that the gridpanel is ...

How to clear a 24-hour-old template from the Angular 1 cache?

I have implemented the following rule to clear template cache in my AngularJS application: myApp.run(function ($rootScope, $templateCache) { $rootScope.$on('$viewContentLoaded', function() { $templateCache.removeAll(); }); }); Howe ...

Image proxy in Node.js

I am currently working on creating a proxy for images using an input URL. Although my code is set up to copy the same headers and return them to the client, I have encountered issues where the response either continues loading indefinitely or shows an er ...

What is the best way to troubleshoot a $http asynchronous request?

Is there a way to pause the program execution in AngularJS $http call after receiving a successful response? I've attempted to set a breakpoint at that point, but it does not halt the execution. I've also tried using the debugger directive, but ...

An error known as "cart-confirmation" has been encountered within the Snipcart platform

I am looking to integrate Snipcart checkout in my Next.js application. However, when I try to validate a payment, I encounter an error message: An error occurred in Snipcart: 'product-crawling-failed' --- Item 1 --- [Item ID] 8 [Item Unique ID] ...

What is the process for turning off deep imports in Tslint or tsconfig?

Is there a way to prevent deep imports in tsconfig? I am looking to limit imports beyond the library path: import { * } from '@geo/map-lib'; Despite my attempts, imports like @geo/map-lib/src/... are still allowed. { "extends": &q ...

What is the best method for implementing a Twitch <script> tag within Vue.js?

In an effort to replicate the functionality I achieved in Angular here, I am now attempting to do so within Vue.JS (2.6+). My goal is to utilize the Twitch API for embedding a Stream, which currently only offers usage through inline HTML: <script src= ...

React Material-UI TextField with Throttling

After exploring React Material UI, I am interested in implementing a TextField component that offers both debouncing and controlled functionality. When we refer to "controlled," we mean that the value persistence is managed externally, with the component a ...

Legend click functionality works well in hiding the bars, but unfortunately, the data values in the charts.js are not being concealed as expected

When I click on the legend, the bar is hidden in the charts.js bar chart. However, the data value associated with the bar is not hidden. I have provided a link to the JS Fiddle code below: Check out the JS Fiddle here: https://jsfiddle.net/npyvw1L8/ var ...

ASP.NET Dynamic Slideshow with Horizontal Reel Scrolling for Stunning

I'm curious if there is anyone who can guide me on creating a fascinating horizontal reel scroll slideshow using asp.net, similar to the one showcased in this mesmerizing link! Check out this Live Demo for a captivating horizontal slide show designed ...

Developing a modular text input component with Material UI and react-hook-form for enhanced reusability

While I was in the process of creating a reusable text field component using Material UI and react-hook-form, I decided to refer to a couple of examples for guidance: Example 1 source: type FormProps<TFormValues> = { onSubmit: SubmitHandler& ...

The carousel spun around, each section moving to the side on its own

One issue I'm facing is that on my page, I have multiple carousel rows. However, when I click on the "next" or "prev" button to navigate through the items in the carousel, it affects all carousels instead of just the one I clicked on. I've attem ...

Encountering an issue with Invariant Violation when attempting to retrieve a frame that is outside of the specified

I have created a VenueList component for my React Native app. I want to utilize the FlatList component to display a list of venues, but I keep encountering an error message that says "Invariant Violation tried to get frame out of range index" (refer to the ...

Discover the steps to linking a dropdown menu to a text input using HTML and JavaScript

I'm currently using Sublime and trying to link a dropdown menu with an input text using html, css, and javascript. When the user selects an option from the dropdown menu, I want the corresponding value to appear in the text input field. For example, i ...

How come the hidden container does not reappear after I click on it?

I'm having an issue with a hidden container that holds comments. Inside the container, there is a <div> element with a <p> tag that says "Show all comments". When I click on this element, it successfully displays the comments. However, cli ...

Utilizing ajax for fetching a data table

I am new to using ajax and have successfully retrieved data from a table. However, I am now trying to pull in an entire data grid but not sure how to achieve this. In my index.php file, I have the following code: <html> <head><title>Aj ...

Is there a way to prevent a web page from automatically refreshing using JavaScript?

I would like my webpage to automatically refresh at regular intervals. However, if a user remains inactive for more than 5 minutes, I want the refreshing to stop. There is an example of this on http://codepen.io/tetonhiker/pen/gLeRmw. Currently, the page ...

I am a newcomer to HTML and I am eager to display the selected options from a <select> element

Can someone help me display the selected licorice flavor, chocolate color, and topping? For example: "Green apple, white, christmas sprinkles." I'm not sure if assigning a numeric value to each option is necessary. I did it on a whim. Please suggest ...

To enhance your React Class Component, make sure to utilize the withStyles feature when

This particular component is not set as a default export component. I am attempting to apply some styles to it but struggling to figure out how to encapsulate it in an HOC. Hence, the current issue where it does not recognize the classes variable. import ...

Add information to the Database seamlessly without the need to refresh the page using PHP in combination with JQuery

Check out my code below: <form action='insert.php' method='post' id='myform'> <input type='hidden' name='tmdb_id'/> <button id='insert'>Insert</button> <p i ...