DOM question in Remove What's Been Clicked


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()?

Replace this line with your code.


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()


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() {

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).


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


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

var remove = function () {

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() {

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


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