views:

77

answers:

4

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!

+5  A: 

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>
Jonathan Sampson
+1  A: 

The exact code you posted works for me.

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

Jason Orendorff
ok yeah it worked for me now. but i wanted to remove a <br /> tag after the clicked link. i tried $(this).next('br').remove() but it didnt work. u got any idea?
weng
OP, see my example - this method removes breaks too.
Jonathan Sampson
+3  A: 

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.

Doug Neiner
A: 

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?

Aditya