Reputation: 391
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?
Upvotes: 0
Views: 10933
Reputation: 3603
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.
Upvotes: 0
Reputation: 82325
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.
Upvotes: 3