Skip to main content

Bug Tracker

Side navigation

#5613 closed bug (worksforme)

Opened December 07, 2009 09:24PM UTC

Closed December 07, 2009 11:40PM UTC

$(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)
  • jquery5613.html (0.8 KB) - added by kimili December 07, 2009 09:24PM UTC.
Change History (1)

Changed December 07, 2009 11:40PM UTC by dmethvin comment:1

resolution: → worksforme
status: newclosed

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.