Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Introduction to jQuery Hello, jQuery! Filtering Matched Elements

Danish Saleem
Danish Saleem
7,965 Points

need help in implementing and understanding not

I am trying to implement .not() function in the index.html(see below) <!DOCTYPE html> <html> <head> </head> <body> <ul> <li>Thing 1</li> <li>Thing 2</li> <li>Thing 3</li> </ul> <script src="http://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <script src="app.js"></script> </body> </html>

with following jQuery

$('li').on('click',function() { $(this).not(":even").text("clicked"); });

so that only the odd number 'li' get the clicked text , but somehow it is not working , need help as what i am doing wrong here

1 Answer

Steven Parker
Steven Parker
221,328 Points

When you apply .not(":even") to a set of elements, it will select every element in the set with an odd-numbered ("not even") index. Note that the index numbers are relative to the set itself and have nothing to do with the element positions relative to their container!

Now $(this) is an element set with only one item in it, so that element has an index number of 0 (even). And .not(":even") will always generate an empty result set when applied to a set with a single item.

If you still want to do what you were attempting another way, this came to mind:

  // test if this item's index within its parent is odd:
  if ($(this).parent().children().index(this) & 1) {

Also, when posting code, always the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. :arrow_heading_down:   Or watch this video on code formatting.