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!
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>
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).
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.
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?