tags:

views:

237

answers:

4

I am handling a hyperlink's click event with a javascript function. I am using jQuery's ajax method to delete a record. Then I want to remove the element I just deleted from the page. The page structure looks like this:

<ul>
  <li>
    <div id="div1"></div>
    <div id="div2">
      <a id="DeleteItem">This is the hyperlink in question</a>
    </div>
  </li>
</ul>

What I want to remove is the li element. My assumption is that I would use the following to remove it:

$("a#DeleteItem").parent.parent.remove();

However this throws an exception stating that parent.parent is null or not an object. I also tried just one level up ($"a#DeleteItem").parent.remove();), but then I get an exception stating object does not support this property or method.

What am I doing wrong?

+5  A: 

It's not working because parent is a function:

$("a#DeleteItem").parent().parent().remove();

You could also use the closest function:

$("a#DeleteItem").closest('li').remove();
Greg
+3  A: 

Try This:

$("#DeleteItem").parents("li:first").remove();

Your primary issue is that parent call is a method call and cannot be accessed like a field. but to avoid the dual call you can do something like described above.

Quintin Robinson
A: 

First of all, you have some basic syntax errors: Use 'parent()' instead of 'parent'

Do you want to delete the 'li' and all of its children (including the clicked-on item), or do you just want to remove the surrounding 'li' tags?

If it's the first case, then you need to do the following:

<a id="DeleteItem" onclick="$(this).parent('div').parent('li').remove();">This is the hyperlink in question</a>

Greg, parent().parent().parent()... will work fine because of the chainability of jQuery. I've used this numerous times in various projects.

Quintin, your approach may not work in all cases because it's going to only target the first 'li' tag in the unordered list, where there may be many.

Josh
Actually it should only target the first li in the direct parent hierarchy beginning from the anchor. The selector is within context and not asking for all the li elements of the UL.
Quintin Robinson
A: 

Thank you for your help. I am new to javascript. This has fixed me right up.

Grant