Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $(this).remove() not working after append

Tags:

jquery

append

I have a div with class="tags" with one predefined hyperlink.

<div class="tags">
     <a href="#">myLink</a>
</div>

And I have function to remove that hyperlink if user clicks on it.

$('.tags a').click(function() {
    $(this).remove();
    return false;
});

And this works with predefined hyperlinks. If I add another links with the help of jQuery (after the page is loaded)

$('.tags').append('<a href="#">newLink</a>');

Function to remove hyperlink (on click) won't be called on these, added links. How to solve this?

like image 865
svenkapudija Avatar asked Mar 12 '12 10:03

svenkapudija


People also ask

How remove and append in jQuery?

jQuery uses: . append(); and . remove(); functions to accomplish this task. We could use these methods to append string or any other html or XML element and also remove string and other html or XML elements from the document.

How to remove function in jQuery?

The remove() method removes the selected elements, including all text and child nodes. This method also removes data and events of the selected elements. Tip: To remove the elements without removing data and events, use the detach() method instead.

How to remove a dom element using jQuery?

remove() method takes elements out of the DOM. Use . remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

How to remove a child element in jQuery?

In jQuery, in order to remove element and content you can use anyone of the following two jQuery methods: Methods: remove() – It is used to remove the selected element (and its child elements). empty() – It is used to removes the child elements from the selected element.


1 Answers

You have to use the live-function:

$(".tags a").live("click", function() {
    // ...
});

Because you are adding the links after the initial load, the standard click event won't be binded to the dynamic added links.

like image 102
kufi Avatar answered Sep 22 '22 06:09

kufi