views:

48

answers:

2

In the below code how to pass the div object inside validate 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>
+2  A: 

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.

Then you can wrap it in a jQuery object, and use .closest() to get the first <div> ancestor, and use .remove() to remove it from the DOM, and clean up any data attached, like event handlers.

Or perhaps preferable to have 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();
});
patrick dw
@patrick:If this div is enclosed in another div.Can we do $(this).closest('div').parent.remove(); And if we do parent .remove() i can use that again right
Rajeev
@rajeev `.closest()` gives the very close Element from the current Element http://api.jquery.com/closest , if you want to remove parent of div, just give a reference to your parent element i.e., an ID or a class, and now use the closest on the parent element, this would be simple and time saving, rather than calling `parent()`, which begins from parent Element (which is time consuming)
Ninja Dude
@Rajeev - @Avinash is right. I updated my answer with an example of placing a class on the `<div>` that you want to target with `.closest()`.
patrick dw
+1  A: 
<div>  blah blah <a href="#" id="remove" > Delete </a>   blah blah </div>

$(function() {
 $('a#remove').click(fnuction() {
     $(this).closest('div').remove();
 });
});
Ninja Dude