I have the following code:
css:
nav div:nth-child(1) { background: red; } nav div:nth-child(2) { background: blue; } nav div:nth-child(3) { background: yellow; }   html:
<nav>  <div>item #1</div>  <div>item #2</div>  <div>item #3</div> </nav>   jquery:
  $(document).ready(function() {        $('.nav div:nth-child').click(function) {           console.log(this);       });    });   edit: i get now: uncaught exception: Syntax error, unrecognized expression: :nth-child
How to click on the nth-child using jquery and get the item number like CSS do? eg: i click on the second one, jquery will return 2
Definition and Usage. The :nth-child(n) selector selects all elements that are the nth child, regardless of type, of their parent. Tip: Use the :nth-of-type() selector to select all elements that are the nth child, of a particular type, of their parent.
Using jQuery :nth-child Selector You have put the position of an element as its argument which is 2 as you want to select the second li element. If you want to get the exact element, you have to specify the index value of the item. A list element starts with an index 0.
Definition and UsageThe :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.
The nth-of-type is very similar to the nth-child pseudo-class. The main difference is that it specifically considers the type of the element getting selected before checking any other logic. Let's use our example from above but apply nth-of-type instead.
$(document).ready(function() {   $('.nav div').click(function() {       var index = $(this).index();       console.log(index);   }); });   index is zero-based
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