Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get child element by index in Jquery?

<div class="second">     <div class="selector" id="selFirst"></div>     <div class="selector" id="selSecond"></div>     <div></div> </div> 

How to get #selFirst using element index not the ID?

this:

var $selFirst = $(".second:nth-child(1)"); console.log($selFirst); 

is returning :

jQuery(div.second) 
like image 975
Davor Zubak Avatar asked Jan 19 '12 13:01

Davor Zubak


People also ask

How to get element index jQuery?

The index() is an inbuilt method in jQuery which is used to return the index of the a specified elements with respect to selector. Parameter: It accepts an optional parameter “element” which is used to get the position of the element. Return value: It returns an integer denoting the index of the specified element.

How to get the nth child of an element in jQuery?

jQuery :nth-child() Selector 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 can get Li tag value in jQuery?

$("#myid li"). click(function() { this.id = 'newId'; // longer method using . attr() $(this). attr('id', 'newId'); });

What is EQ jQuery?

The eq() method returns an element with a specific index number of the selected elements. The index numbers start at 0, so the first element will have the index number 0 (not 1).


2 Answers

If you know the child element you're interested in is the first:

 $('.second').children().first(); 

Or to find by index:

 var index = 0  $('.second').children().eq(index); 
like image 98
Rich O'Kelly Avatar answered Oct 06 '22 08:10

Rich O'Kelly


There are the following way to select first child

1) $('.second div:first-child')
2) $('.second *:first-child')
3) $('div:first-child', '.second')
4) $('*:first-child', '.second')
5) $('.second div:nth-child(1)')
6) $('.second').children().first()
7) $('.second').children().eq(0)
like image 41
Deepak Kumar Avatar answered Oct 06 '22 09:10

Deepak Kumar