Joonas
Joonas

Reputation: 7305

jQuery - If previous element doesnt have specific class then remove that element

I wrote this code, but it doesnt work.

goal:

  1. If span that is previous to ".well-well" is NOT ".dont-remove" then remove that span

  2. However if span that is previous to ".well-well" IS ".dont-remove" then do nothing

"example" here:

http://jsfiddle.net/sAebR/

if( $(".well-well").prev('span').not('.dont-remove') ){ $(".well-well").prev('span').remove(); }

What im getting with this code is that it removes all spans that are previous to ".well-well" and i have no idea why.

What am i doing wrong?

Upvotes: 1

Views: 2853

Answers (3)

Jason McCreary
Jason McCreary

Reputation: 73041

In your case the not statement is always evaluating true because it returns a jQuery object and therefore you are removing all spans.

jQuery works on collections and is chainable. You can simply combine them all into this:

$(".well-well").prev('span').not('.dont-remove').remove();

Check it out in action - http://jsfiddle.net/WFTbF/1/

Upvotes: 1

zneak
zneak

Reputation: 138261

It's because of how you remove elements. If you find elements that match your criteria, you remove every element (with no specific criteria).

It's perfectly legal to use remove on empty collections, so you shouldn't worry about if there are elements or not. Try this instead:

$(".well-well").prev('span').not('.dont-remove').remove();

Upvotes: 1

James Khoury
James Khoury

Reputation: 22369

you don't need the if:

$(".well-well").prev('span').not('.dont-remove').remove()

what your code is say is:

if ($(".well-well").prev('span').not('.dont-remove') != null) 
{
 //remove them all
}

don't worry about the if. The remove() function will look after that.

http://jsfiddle.net/sAebR/2/

Upvotes: 3

Related Questions