DOM question in Remove What's Been Clicked


#1


The chatper says that .remove() will not work in this case because

"jQuery looks for all the .items when the DOM is loaded, so by the time your document is ready, it's already decided there are no .items to .remove()"

I understand that in the beginning the DOM does not contain .items because we haven't added them yet with our button. But after we have added them, won't there be a new DOM that does contain .items? If so, then why can't we use .remove()?


https://www.codecademy.com/courses/web-beginner-en-v6phg/2/4?curriculum_id=50a3fad8c7a770b5fd0007a1


Replace this line with your code.


#2

When we write convenience event listeners, such as .click() they are bound to an element. If the element does not exist when the binding is declared, there is no click event to listen for, AND that line of code will never run again.

That is where event bubbling and delegation come into play. We register a listener on the parent element, which does exist at load time so the binding is in place. This is done with on()

$('.list')

This is the UL that is written in the source code. It is an empty list but it can still be given an event binding.

$('.list').on('click', 'li', function() {
    $(this).remove();
});

As we add new list items there are more elements that we can click. The click event will bubble up to the parent, where the binding exists, and then the event handler will be delegated to the current LI that was just clicked (the current event object).


#3

Thank you. That was a very good explanation. I did not know about event bubbling until now.


#4

The above is known as a callback which we can write independent of our parameters.

var remove = function () {
    $(this).remove();
};

The function is vanilla JS wrapping jQuery code. There will be no conflict or recursion since one is a function, and the other a method. Our event listener will be written,

$('.list').on('click', 'li', remove);

Bear in mind that since the independent function is written as an expression, it must be above the first call to it. To get around this we can hoist our function from anywhere in the source listing by writing a declaration...

function remove() {
    $(this).remove();
}

The function takes its context from the event handler, so $(this) is preserved, that is why there are no parameters.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.