Ad

Event Listeners, JavaScript

- 1 answer

How do I make new content show in my DOM everytime I click a nav link and delete the old one. I get the content one after another when clicking, I want to delete the old one, and show the one I clicked and so on. I'm using an array from a database. This is the code:

$(dataItems).on('click', 'li a', function (event) {
  event.preventDefault();
  let id = $(this).attr('data-code'); // sort them by their data-code

  const childrenItems = []; // push the sorted array items from db to this array
  for (let i = 0; i < Assortments.length; i++) { // This is the array from DB
    if (Assortments[i].AssortimentParentID == id) {
      childrenItems.push(Assortments[i].Name);
    }
  }

  //draw html table
  let perrow = 3, // 3 items per row
       count = 0, // flag for current cell
       table = document.createElement("table"),
       row = table.insertRow();

  for (let i of childrenItems) {
    let cell = row.insertCell();
    cell.innerHTML = i;

    count++;
    if (count%perrow == 0) {
      row = table.insertRow();
    }
  }
  document.querySelector(".deposit-container").appendChild(table);


})

prnt.sc/rdnavd - this is how it looks, as you can see there's 2 tables, I clicked on 2 different categories, I want when clicking a category to show only one table and delete the other clicked before.

Ad

Answer

On this line:
document.querySelector(".deposit-container").appendChild(table);

try replacing appendChild to innerHTML. Append will just keep on adding the element instead of replacing it.

Revised line:
document.querySelector(".deposit-container").innerHTML = table;

EDIT:

If the above didn’t work. Try resetting the child node.

Replace document.querySelector(".deposit-container").appendChild(table); with the below:

let parent = document.querySelector(".deposit-container");

while(parent.firstChild){
  parent.removeChild(parent.firstChild);
}

parent.appendChild(table);

Let me know if this helps...

Ad
source: stackoverflow.com
Ad