Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the 5th element with a specified class in a list and add another class in jQuery

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.

like image 603
Répás Avatar asked Jul 13 '10 09:07

Répás


3 Answers

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>
like image 115
Josh Stodola Avatar answered Sep 29 '22 15:09

Josh Stodola


You can use nth-child of jquery.

$("ul li.hr:nth-child(5)").addClass("green");
like image 15
Krunal Avatar answered Oct 02 '22 15:10

Krunal


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.

like image 7
Borgar Avatar answered Sep 29 '22 15:09

Borgar