Aman Sharma
Aman Sharma

Reputation: 287

Selection of elements using nth-child selectors

$(".sidebar>i:nth-child(3)").on("click", showMenu);
<div class="sidebar">
  <i class="fa fa-volume-up"></i>
	<div class="colorPalette">
	  <button class="submit">Submit</button>
		<p>Color Pallette:</p><br />
		<div class="colors_1">
			<span id="color1"></span>
			<span id="color2"></span>
			<span id="color3"></span>
		</div>
		<div class="colors_2">
		  <span id="color4"></span>
			<span id="color5"></span>
			<span id="color6"></span>
		</div>	
	</div>
	<i class="fa fa-arrow-circle-o-left" title="Back to Menu"></i>
</div>	

I need to select the 2nd (Back to Menu) button. So why nth-child(3) works but not nth-child(2)?

Upvotes: 1

Views: 713

Answers (2)

palaѕн
palaѕн

Reputation: 73976

Since :nth-child(n) selects all children inside a parent element, regardless of what they are. So, in your case:

.sidebar>i:nth-child(3)
// This is the 3rd child, i tag

.sidebar>i:nth-child(2)
// This is the 2nd child, div tag

console.log($('.sidebar>i:nth-child(1)')[0])
console.log($('.sidebar>:nth-child(2)')[0])
console.log($('.sidebar>i:nth-child(2)')[0])
console.log($('.sidebar>i:nth-child(3)')[0])
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar">
  <i class="fa fa-volume-up"></i>
  <div class="colorPalette">Test</div>
  <i class="fa fa-arrow" title="Back to Menu"></i>
</div>

What you need is actually :nth-of-type() selector.

console.log($('.sidebar>i:nth-of-type(1)')[0])
console.log($('.sidebar>i:nth-of-type(2)')[0])
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar">
  <i class="fa fa-volume-up"></i>
  <div class="colorPalette">
    Test
  </div>
  <i class="fa fa-arrow" title="Back to Menu"></i>
</div>

Upvotes: 3

Daniel W Strimpel
Daniel W Strimpel

Reputation: 8470

From JQuery's docs:

The :nth-child(n) pseudo-class is easily confused with :eq(n), even though the two can result in dramatically different matched elements. With :nth-child(n), all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With :eq(n) only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the (n+1)th one (n is 0-based) is selected.

Upvotes: 2

Related Questions