1

I have an UL list :

<ul>
  <li data-sel='foo'></li>
  <li></li>
  <li data-sel='foo'></li>
  <li class='selected'></li>
  <li data-sel='foo'></li>
 </ul>

I can access the first previous element of li.selected who do not have attribute data-sel=foo by using :not selector

var element = $('.selected').prev("li:not([data-sel='foo'])");

But how can i access the first previous element of li.selected who have attribute data-sel=foo ?

Gaurav
  • 8,367
  • 14
  • 55
  • 90

4 Answers4

1

This should work fine:

var element = $('.selected').prev("li[data-sel='foo']");

Demo

Some Guy
  • 15,854
  • 10
  • 58
  • 67
  • I don't think `.has` works: *"Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element."*. http://api.jquery.com/has/ – Felix Kling Sep 06 '12 at 15:32
0

Have you tried the :has selector? http://api.jquery.com/has-selector/

Chase
  • 29,019
  • 1
  • 49
  • 48
0

That is how prev() works, you could use prevAll() like this:

jsFiddle

$('.selected').prevAll('li').not('[data-sel="foo"]').first();

OR

$('.selected').prevAll('li:not([data-sel="foo"]):first');
Gabe
  • 49,577
  • 28
  • 142
  • 181
0

This works:

var element = $('.selected').prevAll("li[data-sel='foo']")[0];

jsFiddle example

j08691
  • 204,283
  • 31
  • 260
  • 272