Despite the popular consensus, you can't use :nth-child
here because it counts all children, regardless of whether or not they match the preceding selector. Only after it grabs the nth element does it compare it to the selector to determine whether it matches. So this: ul li.hr:nth-child(5)
actually gets treated as ul li:nth-child(5).hr
. This might sound weird, but it strictly conforms to the CSS specification (see the jQuery description).
Luckily, jQuery provides the wonderful :eq()
pseudo-class which allows you to filter by a zero-based index, and respects the preceding selector...
$("ul > li.hr:eq(4)").addClass("green");
I even tested this out to make sure it works...
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.green { color:green; font-weight:bold; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("ul > li.hr:eq(4)").addClass("green");
});
</script>
</head>
<body>
<ul>
<li class="a">foo</li>
<li class="b">foo</li>
<li class="hr">foo</li>
<li class="c">foo</li>
<li class="a">foo</li>
<li class="hr">foo</li>
<li class="a">foo</li>
<li class="b">foo</li>
<li class="hr">foo</li>
<li class="c">foo</li>
<li class="a">foo</li>
<li class="hr">foo</li>
<li class="a">foo</li>
<li class="b">foo</li>
<li class="hr">bar</li> <!-- 5th -->
<li class="c">foo</li>
<li class="a">foo</li>
<li class="hr">foo</li>
</ul>
</body>
</html>