I'd like to addClass "green"
to the 5th li.hr
in every ul
containers in my site.
$("ul li.hr").each(function() {
if ($(this).length = 5) {
$(this).addClass("green");
}
});
PS: if its possible with CSS only, tell me how please.
Note that the ul
has mixed elements, like:
<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>
I need the 5th li.hr
.
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>
You can use nth-child of jquery.
$("ul li.hr:nth-child(5)").addClass("green");
You can do this in pure CSS:
/* set rule: select every li.hr element after the 4th */
ul > li.hr ~ li.hr ~ li.hr ~ li.hr ~ li.hr {
color: green;
}
/* unset rule: select every li.hr element after the 5th */
ul > li.hr ~ li.hr ~ li.hr ~ li.hr ~ li.hr ~ li.hr {
/* reverse the rules set in the previous block here */
color: black;
}
Caveat: The ~
selector is not supported by IE6. Works fine on everything else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With