Bug Tracker

Modify

Ticket #5613 (closed bug: worksforme)

Opened 3 years ago

Last modified 3 years ago

$(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:
Blocking: Blocked by:

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

jquery5613.html Download (808 bytes) - added by kimili 3 years ago.

Change History

Changed 3 years ago by kimili

comment:1 Changed 3 years ago by dmethvin

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

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.

Please follow the  bug reporting guidlines and use  jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

View

Add a comment

Modify Ticket

Action
as closed
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.