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?
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.
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.
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.
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.
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