简体   繁体   中英

jquery: how to remove the previous element?

how do i remove a previous element to the triggering one with jquery?

i have tried:

$(this).prev().remove();
$(this).next().remove();

but nothing works!

Be sure jQuery is properly referenced, and all of your syntax is correct:

$("li").click(function(){
  $(this).prev().remove();
});

Works with:

<ul>
  <li><p>Don't delete me!</p></li>
  <li><p>Click me to delete him!</p></li>
  <li><p>Click me twice, to take 'em both out!</p></li>
  <br/> <!-- line break added after OP's comments -->
  <li><p>Click me to remove the line-break!</p></li>
</ul>

Often when seemingly correct jQuery syntax doesn't work (especially with traversing) it is often because you are operating on the wrong element. Take a look at this HTML:

<div>
  Please remove me
</div>
<div>
  <span>Click to remove</span>
</div>

Now, if we wired this up with a click event on the span it is important to first call parent() to get the containing div , and then get the previous element:

$("span").click(function(){
    $(this).parent().prev().remove();
});

A simple call to $(this).prev().remove() would fail because the span is the only child of the div .

The exact code you posted works for me .

Note that this is always set to an element in eg a jQuery click handler, but not in other JavaScript functions (unless you arrange for it to happen that way).

We'll be better able to answer your question if you provide a little more context. Note that this won't necessarily point to the current element unless you are within the context of a handler. What are you trying to achieve here?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM