How to extract img src from div?

I would like to extract the src image from the following html div:

<div class="mini-cart-image">
  <a href="http://marmot.com/equipment-tents-6-person-tents/midpines-6p/889169900013.html">
    <img src="http://s7d2.scene7.com/is/image/marmot/29510_9821_f?$thumb$" alt="Midpines 6P, Orange Spice/Arona, small" title="Midpines 6P, Orange Spice/Arona"/>
  </a>
</div>

      

I have extracted this div from the website using the following code:

var cart_image0 = document.getElementsByClassName("mini-cart-image")[0]
var cart_image0src = cart_image0.getAttribute('src') // null

      

I would like to return the src value. I was thinking about using getAttribute, but this returns null. Is there a way to do this with js methods? My alternative is to manually parse the innerHTML value for the src value. I hope there is a better solution that I am not aware of.

+3


source to share


3 answers


Try querySelector

var cart_image0 = document.querySelector(".mini-cart-image a img").getAttribute('src');

      



or remove a

also from the selector

var cart_image0 = document.querySelector(".mini-cart-image img").getAttribute('src');

      

+4


source


What's going on in your code is that you are selecting an element var cart_image0 = document.getElementsByClassName("mini-cart-image")[0]

with no attribute src

.

This is the reason why you are getting null when you call cart_image0.getAttribute('src')

code



// Select the cart
var cart = document.getElementsByClassName("mini-cart-image")[0];

// Select the img in the cart
var img = cart.getElementsByTagName('img')[0];

// Get the img src attribute with "img.getAttribute('src')" or shorter "img.src"
console.log(img.src);
      

<div class="mini-cart-image">
  <a href="http://marmot.com/equipment-tents-6-person-tents/midpines-6p/889169900013.html">
    <img src="http://s7d2.scene7.com/is/image/marmot/29510_9821_f?$thumb$" alt="Midpines 6P, Orange Spice/Arona, small" title="Midpines 6P, Orange Spice/Arona"/>
  </a>
</div>
      

Run codeHide result


Please note that when cart.getElementsByTagName('img')

you receive a collection with all images in cart

. Therefore, you can iterate or use the very first element img

, as in the example code, with cart.getElementsByTagName('img')[0]

.

0


source


Your problem: var cart_image0 = document.getElementsByClassName("mini-cart-image")[0]

does not reference the element img

.

Try the following:

var cart_wrapper = document.getElementsByClassName("mini-cart-image")[0];
var cart_image0 = cart_wrapper.getElementsByTagName("img")[0]
var cart_image0src = cart_image0.getAttribute('src') // no longer null

      


0


source







All Articles