Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find prev() tags with several selectors

Let's face this situation:

<ul>
  <li>data</li>
  <li class="selector">data2</li>
  <li class="selector2">data3</li>
</ul>

What i'm trying to do is match lis that either have selector class or have class attribute undefined, something like this:

jQuery(function($) {
  $('.selector2').prevAll('li.selector OR li[class==""]');
});

So if I'm running prevAll() on the .selector2, it should return 2 list items. If i run it on .selector, it should return the first list item.

So is there a way to replace that OR ... ?

PS: xpath may work for me too as i'm developing for modern browsers

like image 242
Alex K Avatar asked Jun 09 '12 14:06

Alex K


2 Answers

jQuery(function($) {
  $('.selector2').prevAll('li.selector, li:not([class])');
});

DEMO

Adding in important comment from @pimvdb

This is correct, but be careful - something like .addClass("foo").removeClass("foo") leaves the class attribute behind, although you (might) expect it to be in it's initial state. So it's not quite the same as [class=''].

like image 145
thecodeparadox Avatar answered Oct 01 '22 09:10

thecodeparadox


What i'm trying to do is match lis that either have "selector" class or have class attribute undefined

This XPath expression is equivalent to the pseudo-code in the question:

/ul/li[@class='selector2']/preceding-sibling::li[@class='selector' or not(@class)]

However, a literal translation of the quoted requirement is:

/ul/li[@class='selector' or not(@class)]
like image 42
Dimitre Novatchev Avatar answered Oct 01 '22 10:10

Dimitre Novatchev