Hill79
Hill79

Reputation: 1024

Jquery - selector for nth-child and next 2 children?

I've a fairly standard UL and I'm trying to cycle through the child LI in sets of three at a time, but I'm struggling to get the selector right to pick out the nth-child and then the next two sibling LI.

I was thinking something like...

var start_index = 1; //start with the first <li>

$("li:nth-child("+start_index+"), li:nth-child("+start_index+1+"), li:nth-child("+start_index+2+")")

but I'm clearly missing the point of nth-child as the LI's it picks out are all over the place!

Upvotes: 0

Views: 4771

Answers (4)

Roko C. Buljan
Roko C. Buljan

Reputation: 206689

WORKING DEMO

var li = $("ul.list li");

for(var i = 0; i < li.length; i+=3) {
  li.slice(i, i+3).wrapAll("<li><ul class='new'></ul></li>");
}

$(".new:odd").css("background-color", "#efc");

To invert the result you can use :even selector instead of :odd.

Upvotes: 0

Naga Harish M
Naga Harish M

Reputation: 2789

Try this code

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Style</title>
  <style type="text/css">
  button { display:block; font-size:12px; width:100px; }
  div { float:left; margin:10px; font-size:10px; 
        border:1px solid black; }
  span { color:blue; font-size:18px; }
  #inner { color:red; }
  td { width:50px; text-align:center; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
</head>
<body>
<h2>Change color using jQuery for this list</h2>
<ul id="Mylist">
<li>1st</li>
<li>2nd</li>
<li>3rd</li>
<li>4th</li>
</ul>

<ul id="OtherOne">
<li>1st</li>
<li>2nd</li>
<li>3rd</li>
<li>4th</li>
</ul>
<script type="text/javascript">
var index=1
$('#Mylist li:nth-child('+index+')')
.css("background", "#ff0000")
.nextAll("li").slice(0, 2)
//.nextUntil('#Mylist li:nth-child('+(index+3)+')')
.css("background", "#ff0000");


</script>

</body>
</html>

Upvotes: 1

Jukka Dahlbom
Jukka Dahlbom

Reputation: 1740

From CSS 3 reference:

The :nth-child(an+b) pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree

What you could probably do is define multiple selectors:

li:nth-child(6n+1), li:nth-child(6n+2), li:nth-child(6n+3)

Assuming you want to match elements 1-3, 7-9, 13-15 ... (alternating between groups of three)

Upvotes: 1

Jon
Jon

Reputation: 437904

Would this work for you?

var $lis = $("li:nth-child("+start_index+")"); // Just one li
$lis.add($nth.nextAll("li").slice(0, 2)); // Added its next two siblings

// Now $lis holds (up to) three lis

Upvotes: 0

Related Questions