VAAA VAAA - 3 months ago 9
jQuery Question

Jquery - how to remove element that is not inside a div

Hi I have the following HTML:

<div id="screenlist">
www.sampleurl.com</br>
www.sampleurl.com</br>
www.sampleurl.com</br>
www.sampleurl.com</br>
www.sampleurl.com</br>
www.sampleurl.com</br>
</div>


I have a button that appends a URL in that list:

$('#screenlist').append(url + '</br>');


Now I would like to add an "X" in order to delete any of the links.

$('#screenlist').append(url + ' <span class="delete_icon" /></br>');



How can I attach a click event to that span element that will be dynamic on every element created and that when clicked the complete row is deleted?


Any clue?

Answer

Could you wrap your appended content in span tags?

$('.delete_icon').click(function() {
 $(this).parent().hide('slow');
});
#screenlist span {
  display: flex;
}

.delete_icon {
  background-color: red;
  color: white;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="screenlist">
    <span>www.sampleurl.com<span class="delete_icon">x</span></span>
    <span>www.sampleurl.com<span class="delete_icon">x</span></span>
    <span>www.sampleurl.com<span class="delete_icon">x</span></span>
    <span>www.sampleurl.com<span class="delete_icon">x</span></span>
    <span>www.sampleurl.com<span class="delete_icon">x</span></span>
</div>