Opened 13 years ago
Closed 13 years ago
#5613 closed bug (worksforme)
$(this).is(':odd') selector not returning correct value in an $().each loop
Reported by: | kimili | Owned by: | |
---|---|---|---|
Priority: | minor | Milestone: | 1.4 |
Component: | unfiled | Version: | 1.4a1 |
Keywords: | Cc: | ||
Blocked by: | Blocking: |
Description
When one loops through elements in a jQuery object using .each()
, $(this).is(':odd')
always returns false (and $(this).is(':even')
always returns true) - the selector always sees the index as 0 in this case.
Test case:
HTML
<ul> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> </ul>
JS
$(document).ready(function(){ $('li').each(function(){ $(this).addClass($(this).is(':odd') ? 'odd' : 'even'); }); });
I've also attached the test case in an HTML file.
I encountered this bug in 1.3.2 and it is still present in 1.4a1.
I know there are other ways to easily get around this, but this was unexpected behavior.
Attachments (1)
Change History (2)
Changed 13 years ago by
Attachment: | jquery5613.html added |
---|
comment:1 Changed 13 years ago by
Resolution: | → worksforme |
---|---|
Status: | new → closed |
Note: See
TracTickets for help on using
tickets.
It's working as it should. In your example,
$('li')
is a jQuery object that contains all the LI elements in the document.$(this)
is a jQuery object that contains a single LI element. It just happens to be one of the ones that is also in the first collection, but there is nothing in the jQuery object that denotes that. The decision about even/odd is made based on the current jQuery object. To select based on the element's count relative to its parent element in the document, you could try the:nth-child(odd)
selector instead.