lol thank you. Your input has been a tremendous help as I learn.
Completely forgot. Were you also able to resolve the issue around removing multiple elements at once?
Not yet , ive been tinkering but nothing seems to solve the issue. I deployed the app here for testing
https://ezmanagers.com/Projects/Timeline/index.html
ive been researching promises await and async , to use it in the foreach loop when it iterates to remove the selected items. I haven’t solved how to implement it yet.
function removeElement() {
// somehow implement async/await to removal selected items at the same time.
for (let i = 0; i < selected.length; i++) {
selected[i].remove()
}
}
This may be worth a shot - try removing the items in reverse:
function removeElement() {
// somehow implement async/await to removal selected items at the same time.
for (let i = selected.length - 1; i >= 0; i--) {
selected[i].remove()
}
}
It Worked! Removing in reverse order did the job. I don’t understand why just yet, but it did. I guess its time to do some research. Thanks for the suggestion.
@senocular can go into more detail here, but the TL;DR is that you want to ensure the list you are iterating through does not change from under you.
When you are getting a list of items using something like getElementsByClassName, you are getting a live collection of DOM elements. When you remove an element (or add an element), the list of items updates in real-time. This means that while you are looping through your items, the list is updating as each item gets removed.
Going in reverse doesn’t change your list from getting updated, but it is updating in your favor. The item that is removed from your list is the same as the item you just removed.
One way of addressing this problem is to use querySelectorAll
to find all of your DOM elements that are selected. The querySelectorAll
method doesn’t return a live list of impacted DOM elements/nodes. This means you removing DOM elements won’t impact the contents of your list that you are iterating through
Ahhh I see. I enjoyed the article and again learned something new! I refactored my code to use the querySelector
and querySelectorAll
commands and will only use these going forward. Being able to use attribute selectors within the commands is pretty slick. I can pretty much grab anything I want in the DOM with those two commands .