How to select a single child element using jQuery?
Solution 1:
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.
Solution 2:
No. Every jQuery function returns a jQuery object, and that is how it works. This is a crucial part of jQuery's magic.
If you want to access the underlying element, you have three options...
- Do not use jQuery
- Use
[0]
to reference it -
Extend jQuery to do what you want...
$.fn.child = function(s) { return $(this).children(s)[0]; }
Solution 3:
Maybe in this way?
$('img', this)[0]
Solution 4:
You can target the first child element with just using CSS selector with jQuery:
$(this).children('img:nth-child(1)');
If you want to target the second child element just change 1 to 2:
$(this).children('img:nth-child(2)');
and so on..
if you want to target more elements, you can use a for loop:
for (i = 1; i <= $(this).children().length; i++) {
let childImg = $(this).children("img:nth-child("+ i +")");
// Do stuff...
}