views:

554

answers:

2

It surprised me that Sizzle (the selector engine jQuery uses) comes with a built-in :nth-child() selector, but lacks an :nth-of-type() selector.

To illustrate the difference between :nth-child() and :nth-of-type() and to illustrate the problem, consider the following HTML document:

<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <title>:nth-of-type() in Sizzle/jQuery?</title>
  <style>
   body p:nth-of-type(2n) { background: red; }
  </style>
 </head>
 <body>
  <p>The following CSS is applied to this document:</p>
  <pre>body p:nth-of-type(2n) { background: red; }</pre>
  <p>This is paragraph #1.</p>
  <p>This is paragraph #2. (Should be matched.)</p>
  <p>This is paragraph #3.</p>
  <p>This is paragraph #4. (Should be matched.)</p>
  <div>This is not a paragraph, but a <code>div</code>.</div>
  <p>This is paragraph #5.</p>
  <p>This is paragraph #6. (Should be matched.)</p>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"&gt;&lt;/script&gt;
  <script>
   $(function() {
    // The following should give every second paragraph (those that had red backgrounds already after the CSS was applied) an orange background.
    // $('body p:nth-of-type(2n)').css('background', 'orange');
   });
  </script>
 </body>
</html>

Since Sizzle uses the browser-native querySelector() and querySelectorAll() methods if those are present (i.e. in browsers that already implement the Selectors API), stuff like $('body p:nth-child'); will of course work. It won’t work in older browsers though, because Sizzle has no fallback method for this selector.

Is it possible to easily add the :nth-of-type() selector to Sizzle, or to implement it in jQuery (by using the built-in :nth-child() selector, perhaps)? A custom selector with parameters would be nice.

+1  A: 

I can't pretend to know how nth-of-type is implemented, but jQuery does provide a mechanism by which you can create your own custom selector.

The following question deals with custom selectors, and may provide a useful insight to you

http://stackoverflow.com/questions/1940574/what-useful-custom-jquery-selectors-have-you-written

James Wiseman
Yes, I am aware of this… I should probably add that to my post.
Mathias Bynens
+2  A: 

Hi, the jQuery plugin moreSelectors has support for nth-of-type (and many other selectors). I suggest either using that, or simply implement a simple plugin that only implements the exact selectors you need. You should be able to copy-paste code from there.

Happy hacking!

Emil Stenström