Home > Enterprise >  Select image from first div only using jquery selector
Select image from first div only using jquery selector

Time:03-01

I want to grab image src from first div with div class and image class, however another div and image also has same class so I am unable to get it.

console.log(
    $("div.DetailSection_content").find("img:first").attr("src")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
    <div >
      <div >
        <div >
          <img src="https:img_url_1" alt=""  data-index="0">
        </div>
      </div>
    </div>
  </div>
</div>

<div >
  <div >
    <div >
      <div >
        <div >
          <img src="https:img_url_2" alt=""  data-index="0">
        </div>
      </div>
    </div>
  </div>
</div>

CodePudding user response:

The problem with your code is that it will only the src for one image when you use .attr("src")

in your case :first does not do anything based on your code, because you only have 1 image inside each <div >

You can do it like this:

var imgs = $('div.DetailSection_content img').map(function() {
  return $(this).attr("src")
}).get();

This will return an array of the img src from $('div.DetailSection_content img')

Demo

var imgs = $('div.DetailSection_content img').map(function() {
  return $(this).attr("src")
}).get();
console.log(imgs)

console.log(
    $("div.DetailSection_content img").attr("src")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
    <div >
      <div >
        <div >
          <img src="https:img_url1" alt=""  data-index="0">
        </div>
      </div>
    </div>
  </div>
</div>

<div >
  <div >
    <div >
      <div >
        <div >
          <img src="https:img_url2" alt=""  data-index="0">
        </div>
      </div>
    </div>
  </div>
</div>

CodePudding user response:

try

const src = $('div.DetailSection_content img')[0].src

$(() => {

const src = $('.DetailSection_content img')[0].src

console.log(src)

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
    <div >
      <div >
        <div >
          <img src="https:img_url_1" alt=""  data-index="0">
        </div>
      </div>
    </div>
  </div>
</div>

<div >
  <div >
    <div >
      <div >
        <div >
          <img src="https:img_url_2" alt=""  data-index="0">
        </div>
      </div>
    </div>
  </div>
</div>

  • Related