Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the 2nd child element

I am still new in jquery and I have this code

<div>
   abcsdf
   <div> first child</div>
   <div> second child</div>
</div>

I wanted to get the second child, they are dynamically populated using append and I don't know how to get it.

I wanted to display

$('the second element inner html here').dialog() etc..

Hoping someone can help me.

Thanks

like image 266
Carls Jr. Avatar asked Mar 26 '11 06:03

Carls Jr.


People also ask

How do you select an element for a second child in CSS?

The :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.

How do you select the second p element in CSS?

Use the CSS :nth-last-of-type(n) selector to select every <p> element that is the second <p> element of its parent, counting from the last child.

How do you target a second child in Javascript?

you just need to load it into your website, then you can target the element in your exemple using: $('. parent div:nth-child(2)') It's that easy.


2 Answers

A number of ways to do this one. I'm going to assume the toplevel div has an id of 'top'. This is probably the best one:

$('#top > :nth-child(2)').whatever();

or

$('#top').children(':first-child').next().whatever();

or if you know for a fact there are at least 2 children

$($('#top').children()[1]).whatever();
like image 105
issa marie tseng Avatar answered Oct 10 '22 14:10

issa marie tseng


check this link

Nth child selecter

Or you can try :eq Selector also

Eq selector

like image 38
Harish Avatar answered Oct 10 '22 12:10

Harish