Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery nth-child click

Tags:

html

jquery

click

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

like image 815
E.G. Avatar asked Nov 26 '11 02:11

E.G.


People also ask

What is nth child in jQuery?

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.

How do I target a second child in jQuery?

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.

How do I choose a multiple nth child?

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.

What's the difference between the nth of type () and Nth child () selectors?

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.


1 Answers

$(document).ready(function() {   $('.nav div').click(function() {       var index = $(this).index();       console.log(index);   }); }); 

index is zero-based

like image 171
hope_is_grim Avatar answered Sep 19 '22 14:09

hope_is_grim