: enésimo-tipo () no jQuery / Sizzle?
Me surpreendeu queChiar (o mecanismo seletor que o jQuery usa) é fornecido com um:nth-child()
seletor, mas não possui um:nth-of-type()
seletor.
Para ilustrar a diferença entre:nth-child()
e:nth-of-type()
e para ilustrar o problema, considereo seguinte 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>
Como o Sizzle usa o navegador nativoquerySelector()
equerySelectorAll()
métodos, se estiverem presentes (ou seja, em navegadores que já implementam oAPI de seletores), coisas como$('body p:nth-child');
claro que vai funcionar. No entanto, ele não funciona em navegadores antigos, porque o Sizzle não possui um método de fallback para esse seletor.
É possível adicionar facilmente o:nth-of-type()
seletor para Sizzle ou para implementá-lo no jQuery (usandoo embutido:nth-child()
seletor, possivelmente)? UMAseletor personalizado com parâmetros seria bom.