How to remove cloned items

With jQuery, I am trying to make a function similar to the filtering system used on this website ( example )

If you click one of the filtering elements, it will be displayed in another area. You can delete the selected filter by simply clicking it.

My code works to clone a filter element and display it in a different area, but I am having trouble deleting it.

I spent a lot of time researching, but could not find a solution, so your help would be greatly appreciated!

Here is my code

--- --- HTML

<div id="filter-selected> <ul> <!--selected element comes here --> </ul> </div> <div id="filter-options"> <ul> <li> <!--clicking this list will clone itself to the above area--> <span>Value1</span> </li> <li> <!--clicking this list will clone itself to the above area--> <span>Value2</span> </li> </ul> </div> 

--- jquery ---

 $('#filter-options > ul > li').click(function(event){ var $filter = $(this).children('span').clone(); $filter.appendTo('#filter-selected > ul').wrap('<li class="filtering"></li>'); }); $(.filtering').click(function(){ $(this).remove(); }); 
+4
source share
2 answers

Because items are created dynamically, event delegation is required

 $('#filter-selected').on('click', '.filtering', function(){ $(this).remove(); }); 
+3
source

You are missing the quote line on the left side of ' of .filtering , which may be a problem.

 $(.filtering').click(function(){ 
+1
source

Source: https://habr.com/ru/post/1497912/


All Articles