Sylar Sylar - 4 months ago 22
Javascript Question

How to properly use jquery prev?

How to select the previous element using prev()? I want when I click

icon 1
it removes the
span
.

html.erb

# inside a loop -- notice the loop!.
<span data-id="foo_span">
<i data-id="bar">icon 1</i>
<i>icon 2</i>
</span>


JavaScript:

$("[data-id=bar]").click(function(e){
e.preventDefault();
//$(this).prev("[data-id=foo_span]").remove();
$(this).prev().remove();
});


Am I using
prev()
correctly? Based on the examples, it uses
.css
. What's the correct method to remove the span tag?
i
must be inside a span tag.

Answer

You need to use parent() method and prev() method is using to get the immediately preceding sibling of the element.

$(this).parent().remove();
Comments