Mi8Guy
Mi8Guy

Reputation: 37

How to grab the src of img tag that is within an anchor tag with javascript?

The Html Code is as follows, I have more of these tags hence the class:

<a class = "openmodal">
   <img class="case" src="aqua.jpg>
   <h4>Aqua</h4>        
</a>

The javascript is as follows,basically i want to grab the img tag so that i can get its src:

var btns = document.getElementsByClassName("openmodal");
for(let i=0;i<btns.length;i++){
    var x = btns[i].firstChild;
    console.log(x);
   btns[i].onclick = function() {
      modal.style.display = "block";
   }
}

Upvotes: 0

Views: 886

Answers (4)

Yasir
Yasir

Reputation: 687

try document.getElementsByTagName("img") to get images only

HTML

<a class = "openmodal">
   <img class="case" src="aqua.jpg" />
   <h4>Aqua</h4>        
</a>
<img class="case" src="aqua1.jpg" />

JS

var imgclasses =  document.getElementsByClassName('openmodal');
for (var imgclass of imgclasses) {
  var imgs = imgclass.getElementsByTagName("img");
  for(let i=0;i<imgs.length;i++){
      var x = imgs[i];
      console.log(x.src);
      imgs[i].onclick = function() {
        modal.style.display = "block";
      }
  }
};

codepen: https://codepen.io/YasirKamdar/pen/zRWqyg

Upvotes: 1

NnN
NnN

Reputation: 463

You could try in this way to get src attribute of an img.

var ele = document.getElementsByClassName('openmodal');
if(ele.length > 0){
  for (i = 0; i < ele.length; i++) {
      for(j = 0; j < ele[i].children.length; j++){
        if(ele[i].children[j].hasAttribute('src')){
          console.log(ele[i].children[j].getAttribute('src'));
        }
      }
  }
}
<a class="openmodal">
   <img class="case" src="aqua.jpg">
   <h4>Aqua</h4>        
</a>

Upvotes: 0

CodeLover
CodeLover

Reputation: 569

Much faster and better approach.

var btns = document.getElementsByClassName("openmodal");
var len = btns.length;
while(len--){
   var btn = btns[len];
   btn.children[0].onclick = function() {
      console.log(this.src);
   };
}
<a class = "openmodal">
   <img class="case" src="aqua.jpg">
   <h4>Aqua</h4>        
</a>
<a class = "openmodal">
   <img class="case" src="aqua2.jpg">
   <h4>Aqua</h4>        
</a>

Upvotes: 0

brk
brk

Reputation: 50326

Use querySelectorAll

   // will give all anchor tag with this class
var btns = document.querySelectorAll(".openmodal");
// iterating this collection
for (let i = 0; i < btns.length; i++) {
  // inside this element it is querying for img tag & adding event listener to it
  btns[i].querySelector('img').addEventListener('click', function() {
    // get the src attribute from it
    var m = this.getAttribute('src');
    console.log(m)
  })
}
<a class="openmodal">
  <img class="case" src="aqua.jpg" alt="img">
  <h4>Aqua</h4>
</a>

<a class="openmodal">
  <img class="case2" src="aqua2.jpg" alt="img">
  <h4>Aqua2</h4>
</a>

Upvotes: 2

Related Questions