why jQuery .find() only return first element?

Viewed 183

I am trying to use find() function to get all my children element, with each() function I am expecting it return all element, but it only get first element. Is there any misunderstanding with these two functions?

if ($('.test').length > 0) {
  var srcset;
  $(".test").each(function(index, ele) {
    srcset = $(ele).find("source").attr("srcset");
    console.log(srcset);
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<picture class="test">
  <source srcset="###">
  <source srcset="###">
  <source srcset="###">
  <img src="#" alt="">
</picture>

2 Answers

You are getting the first one because .attr() will return the first element attribute, you have to loop through the selection using .each(), and one more thing you can use ".test source" selector directly, here is a working snippet:

if ($('.test').length > 0) {
  srcset = $(".test source");
  srcset.each(function(i, el){
    console.log($(el).attr('srcset'));  
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<picture class="test">
  <source srcset="###">
  <source srcset="###">
  <source srcset="###">
  <img src="#" alt="">
</picture>

Actually, .find("source") returns all the elements as you can see here:

$(".test").each(function() {
  var source = $(this).find("source");
  console.log(source.length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<picture class="test">
  <source srcset="###">
  <source srcset="###">
  <source srcset="###">
  <img src="#" alt="">
</picture>

You can see source.length returns 3 above, but the issue is with .attr("srcset"). When we use .attr() it only returns the value of the first matched element in the collection. To fix this issue you simply need to loop through all source elements and then get srcset like:

var srcset;
$(".test source").each(function() {
  srcset = $(this).attr("srcset");
  console.log(srcset);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<picture class="test">
  <source srcset="/abc">
  <source srcset="/123">
  <source srcset="/example/object/">
  <img src="#" alt="">
</picture>

Related