开发者

jQuery parent.parent removal

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开发者_Python百科 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?


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();


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜