Reputation: 7305
I wrote this code, but it doesnt work.
goal:
If span that is previous to ".well-well" is NOT ".dont-remove" then remove that span
However if span that is previous to ".well-well" IS ".dont-remove" then do nothing
"example" here:
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
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
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
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.
Upvotes: 3