Bug Tracker

Ticket #6474 (closed bug: worksforme)

Opened 5 years ago

Last modified 5 years ago

strange behavior of has() and eq()

Reported by: mitallast@… Owned by:
Priority: Milestone: 1.4.2
Component: selector Version: 1.4.2
Keywords: eq, has Cc:
Blocking: Blocked by:

Description

some code html:

<select name="1"> <option>0</option> <option>1</option> </select>

<select name="2"> <option>0</option> <option>1</option> <option>2</option> </select>

<select name="3"> <option>0</option> <option>1</option> <option>2</option> </select>

I expect, that query $('select:has(option:eq(2))') return select[name=2] and select[name=3], but returned nothing. But query $('select').has('option:eq(2))') return only select[name=2].

It's like as "has" selector find all options, instead of options in current select as in find function.

Change History

comment:1 Changed 5 years ago by rsinton

Not a bug.

:eq(n) doesn't do what you're expecting: it selects element n from an array of results -- check the docs for more details.

What you want is $('select:has(option:contains(2))').

Your second example is working correctly, in that it finds the third option element in the document ( eq(2), because the array is zero-indexed), then returns the select element that does contain that option element.

Some examples to clarify:

<html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.js"></script>
    <script type="text/javascript">

      $( document ).ready( function() {
        alert( $( 'select:has(option)' ).text() );              // 'a b c d e f g h i'
        alert( $( 'option:contains(c)' ).text() );              // 'c'
        alert( $( 'select:has(option:contains(c))' ).text() );  // 'c d e'
        alert( $( 'select' ).has( 'option:eq(4)' ).text() );    // 'c d e'
        alert( $( 'select' ).has( 'option:eq(5)' ).text() );    // 'f g h i '
      });
    </script>
  </head>
  <body>
    <select name="1"> <option>a</option> <option>b</option> </select>
    <select name="2"> <option>c</option> <option>d</option> <option>e</option> </select>
    <select name="3"> <option>f</option> <option>g</option> <option>h</option> <option>i</option> </select>
  </body>
</html>}}}

comment:2 Changed 5 years ago by dmethvin

  • Status changed from new to closed
  • Resolution set to worksforme

Yep, rsinton is right. Take a look at the :nth-child selector as well.

Note: See TracTickets for help on using tickets.