: nth-of-type () en jQuery / Sizzle?
Me sorprendió queChisporrotear (el motor selector jQuery usa) viene con un incorporado:nth-child()
selector, pero carece de un:nth-of-type()
selector.
Para ilustrar la diferencia entre:nth-child()
y:nth-of-type()
y para ilustrar el problema, considereel siguiente documento 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>
Desde Sizzle usa el navegador nativoquerySelector()
yquerySelectorAll()
métodos si están presentes (es decir, en los navegadores que ya implementan elSelectores API), Cosas como$('body p:nth-child');
Por supuesto funcionará. Sin embargo, no funcionará en navegadores más antiguos, ya que Sizzle no tiene un método alternativo para este selector.
¿Es posible agregar fácilmente la:nth-of-type()
Selector para Sizzle, o para implementarlo en jQuery (usandoel incorporado:nth-child()
selector, quizás)? UNAselector personalizado con parametros sería bueno.