Sizzle (jQuery が使用するセレクター エンジン) には組み込みの:nth-child()
セレクターが付属しているのに、セレクターがないことに驚きました:nth-of-type()
。
:nth-child()
ととの違い:nth-of-type()
を説明して問題を説明するために、次の HTML ドキュメントを考えてみましょう。
<!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"></script>
<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>
Sizzle はブラウザー ネイティブのメソッドquerySelector()
とquerySelectorAll()
メソッドが存在する場合 (つまり、セレクター APIを既に実装しているブラウザー内)にそれらを使用するため$('body p:nth-child');
、もちろん動作します。ただし、Sizzle にはこのセレクターのフォールバック メソッドがないため、古いブラウザーでは機能しません。
:nth-of-type()
セレクターを Sizzleに簡単に追加したり、jQuery に実装したりすることは可能ですか (おそらく組み込みの:nth-child()
selectorを使用して)? パラメータ付きのカスタムセレクターがいいでしょう。