Search code examples
javascriptjquery-selectorssizzle

Sizzle returning only one element while selector matches two


Sizzle does not return all the elements which match the selector. Here is JSBin Demo showing the problem.

HTML

<h4> Playing with Sizzle JS </h4>

  <ul class="list">
    <li> Item 1 </li>
    <li class="row"> Item 2 </li>
    <li class="row"> <span>Item 3</span> </li> 
    <li class="divider">List item with unique class name </li>
  </ul>

  <ul class="list">
    <li> Item 1 </li>
    <li class="row"> Item 2 </li>
    <li class="row"> <span>Item 3</span> </li> 
    <li class="divider">List item with unique class name </li>
  </ul>

JS

var selector = 'UL.list > LI:eq(1)';
var elements = Sizzle(selector);

console.log(elements.length); //Says 1

My Question is:

Why it returns only 1 element while there are 2 elements which match the selector? How can I make sizzle to return all matching elements ?


Solution

  • UL.list > LI:eq(1) will only ever return one element: the 2nd element that matches UL.list > LI, as indicated by :eq(1).

    If you're looking for all li elements, remove the :eq().

    If you're looking for every li that is the second child, use :nth-child():

    var elements = Sizzle('UL.list > LI:nth-child(2)');