&nbs...">

Passing self object in jquery

In the code below, how to pass a div object inside a validation function

<div><input type="text"></input>&nbsp;&nbsp;&nbsp&nbsp;<a href="#" onclick="validate("Hot to pass the div objevt here")"</input> <script> function validate() { ..... ..... Finally remove the div } </script> 
+6
jquery jquery-ui jquery-validate jquery-selectors
source share
2 answers

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(); }); 
+10
source share
 <div> blah blah <a href="#" id="remove" > Delete </a> blah blah </div> $(function() { $('a#remove').click(function() { $(this).closest('div').remove(); }); }); 
+4
source share

All Articles