Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a single child element using jQuery?

Using jQuery how do I select a single child element? I've looked at the Traversing API and know I can select all the immediate children img elements like this:

$(this).children('img'); 

And to select the first child img element I could use a subscript like this:

$(this).children('img')[0]; 

But I guess I'm kind of surprised I can't do this:

$(this).child('img'); // no subscript, returns single element 

Or have I missed something?

like image 503
Jonathon Watney Avatar asked Sep 24 '09 20:09

Jonathon Watney


People also ask

How do I select a specific child in Javascript?

Select the parent element whose child element is going to be selected. Use . querySelector() method on parent. Use the className of the child to select that particular child.

How do you get children of children in jQuery?

Definition and Usage. The children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.

How do you get the children of the $( this selector?

Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.


1 Answers

I think what you want to do is this:

$(this).children('img').eq(0); 

this will give you a jquery object containing the first img element, whereas

$(this).children('img')[0]; 

will give you the img element itself.

like image 109
Greg Avatar answered Sep 28 '22 21:09

Greg