Alina Khachatrian
Alina Khachatrian

Reputation: 757

can't inject DOM element with node.insertBefore() approach

I have a list of items sorted in the alphabetic way. The idea was is to inject a corresponding letter from alphabetArr array after <li> with an id from DOMElementsArr array. What am I doing wrong?

No errors in the console but it doesn't work.

Arrays:

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']

Here is my approach:

//create function that injects new element
function insertAfter(el, referenceNode) {
  referenceNode.parentNode.insertBefore(el, referenceNode.nextSibling);
}

//function that loops 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();

Upvotes: 2

Views: 84

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115242

In your current code you are just creating a single element, then iterating and updating its content, then getting element on next loop and finally you are calling the insertAfter function only once with last values.

To make it works, you have to combine both the loop and then move the insertion code to the loop.

//create function that injects new element
function insertAfter(el, referenceNode) {
  referenceNode.parentNode.insertBefore(el, referenceNode.nextSibling);
}

//function that loops through both arrays
function injectAllAlphabetLetters() {
  // iterate until last element of minimum length array(to avoid problem in case array length are different)
  for (let i = 0; i < alphabetArr.length && i < DOMElementsArr.length; i++) {    
    //Create new element and set properties
    let newEl = document.createElement('li');
    newEl.className = 'titles alphabet';    
    newEl.innerHTML = alphabetArr[i][0];

    // get the element based on id
    let ref = document.getElementById(DOMElementsArr[i]);    
    // call function to insert
    insertAfter(newEl, ref);
  }

}

injectAllAlphabetLetters();

Upvotes: 2

Related Questions