I am trying to make a web app (technically it’s not a web app, I know), that traverses the DOM and manipulates elements.
My goal is to have trash buttons that when you click on them they move the item to the TRASH section below.
There are actually a few errors in the console. First, list is not defined; I changed that to document, then on clicking the trash button it throws at this point:
which is not a valid assignment. Looking at your snippet though, there are some issues with this line:
let trashSelected = document.getElementsByClassName('trashButton Fa').removeChild;
Now .getElementsByClassName() returns a list of elements, but you can only call .removeChild() on single elements And to actually call it, you need to add the parens; also, it expects the child to be removed as its argument. Did you mean something like
const elementToRemove = event.target.closest('li')
elementToRemove.parentNode.removeChild(elementToRemove)
// Or in modern browsers just:
event.target.closest('li').remove()
or
const trashList = document.querySelector('.trashList')
// then later:
trashList.appendChild(event.target.closest('li'))
I believe the second option you picked works best for me for now. I am new to mastering DOM manipulation and traversing using vanilla Javascript. The dot notation was confusing me a bit.
Couple questions/comments…
1.) Not sure why the list error didn’t show up, I was using Chrome Dev tools. My console showed nothing.
2.) Why is it you didn’t need to remove anything from the list element using something like removeChild();?? Or does appendChild(); remove and add it all in one steady, fluid process, as opposed to me needing to code for two methods/properties to perform that? (Cause that’s what I thought I had to do)
3.) Never heard of the closest(); method outside of JQuery. Interesting explanation from MDN on how to use closest();.
4.) In regards to your syntax, I’ve never seen a method inside a method before! Why did you have to retype event.target for this trashList.appendChild(event.target.closest('li'))??
Doesn’t the javascript interpreter understand what I want selected from the previous line?
Well .appendChild() will append this exact element, not a copy of it. And since an element can’t be at multiple places in the document simultaneously, it’ getting detached from its old parent first.
Yes there are actually a few newer methods in the DOM standard resembling jQuery like this; check out the child node and parent node interfaces. You only have to be careful with the browser compatibility… :-/
Not sure what you mean… why retype? It’s the first time event.target gets referenced in that snippet…