S S
S S

Reputation: 1503

How to get the image on button click event?

I have added div with image dynamically. So finally, my complete div looks like this:

<div class ="main-wrapper">
    <div class = "inner">
        img src="data:image/jpeg....> 
    </div>
    <div class = "inner">
        img src="data:image/jpeg....> 
    </div>
    <div class = "inner">
        img src="data:image/jpeg....> 
    </div>
    <div class = "inner">
        img src="data:image/jpeg....> 
    </div>
</div>

Now, I need to get the image i.e only data:image/jpeg....

$("#main-wrapper").on('click', '.inner', function(e) {
    var data  = e.currentTarget.innerHTML;
});

which return all the HTML as well.

<img src="data:image/jpeg;base64

How to can get only the name?

Upvotes: 1

Views: 103

Answers (2)

Arun Kumar
Arun Kumar

Reputation: 49

img element inside the div can be accessed from the children array.

src attribute can be accessed from the image dom element as .src

<div class ="main-wrapper">
    <div class = "inner">
        <img src="data:image/jpeg...."/> 
    </div>
    <div class = "inner">
        <img src="data:image/jpeg...."/> 
    </div>
    <div class = "inner">
        <img src="data:image/jpeg...."/> 
    </div>
    <div class = "inner">
        <img src="data:image/jpeg...."/> 
    </div>
</div>

<script>
$(".main-wrapper").on('click', '.inner', function(e) {
    console.log(e.currentTarget.children[0].src);
});
</script>

Upvotes: 1

J&#243;zef Podlecki
J&#243;zef Podlecki

Reputation: 11283

There is attr method for that

function blobToDataURL(blob, callback) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.onload = ({
      target: {
        result
      }
    }) => resolve(result);
    fileReader.readAsDataURL(blob);
  })
}


$(function() {

  fetch("https://i.picsum.photos/id/842/100/100.jpg")
    .then(response => response.blob())
    .then(blobToDataURL)
    .then(dataUri => {
      $('.image').attr("src", dataUri)
    })


  $(".main-wrapper").on('click', '.image', function(e) {
    console.log($(this).attr("src"));
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main-wrapper">
  <div class="inner">
    <img class="image" src="">
  </div>

</div>

Upvotes: 1

Related Questions