Event Listeners, JavaScript
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.
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...
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM