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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With