Passing self object in jquery
In the code below, how to pass a div object inside a validation function
<div><input type="text"></input>   <a href="#" onclick="validate("Hot to pass the div objevt here")"</input> <script> function validate() { ..... ..... Finally remove the div } </script> HTML:
<div class='elementToRemove'> <div> <a href="#" onclick="validate(this)">some text</a> </div> </div> JavaScript:
function validate( elem ) { $(elem).closest('div.elementToRemove').remove(); } In the validate() function, elem will represent the <a> element that received the event.
You can then wrap it in a jQuery object and use .closest() to get the first ancestor <div> and use .remove() to remove it from the DOM and clear all attached data, like event handlers.
Or, perhaps it is advisable that jQuery take care of your event handlers:
HTML:
<div class='elementToRemove'> <div> <a href="#" class="someClassName">some text</a> </div> </div> JQuery
$('a.someClassName').click(function() { $(this).closest('div.elementToRemove').remove(); }); <div> blah blah <a href="#" id="remove" > Delete </a> blah blah </div> $(function() { $('a#remove').click(function() { $(this).closest('div').remove(); }); });