如何使用javascript获取锚标记内的img标记的src?

时间:2018-02-20 06:21:26

标签: javascript html

Html代码如下,我有更多这些标签因此类:

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

javascript如下,基本上我想抓取img标签,以便我可以得到它的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";
   }
}

4 个答案:

答案 0 :(得分:2)

使用querySelectorAll

&#13;
&#13;
   // 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)
  })
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试document.getElementsByTagName("img")仅获取图片

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

答案 2 :(得分:0)

更快更好的方法。

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>

答案 3 :(得分:0)

您可以尝试以这种方式获取src的{​​{1}}属性。

&#13;
&#13;
img
&#13;
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'));
        }
      }
  }
}
&#13;
&#13;
&#13;