1

I am using tag manager to dynamically place information from the website into an html element using custom javascript. My code at the moment is this. PS I can't figure out how to post properly. This actually starts with

function(){
    console.log("Start image variable");
    var element = document.getElementsByClassName("MagicZoomPlus")[0];
    console.log(element);
    var image = element.getAttribute("img src").innerHTML;
    console.log(image);
    return image;
}

This returns the following debug information

unreachable code after return statement[Learn More]  trustlogo.js:28:123
Start image variable  gtm.js:1:42
<a id="ZoomGallery" href="/uploads/products/892_3521-05 .jpg" class="MagicZoomPlus" title="Franklin Paradigm Grey Sofa">  gtm.js:1:136
undefined  gtm.js:1:186

The html on the site I am trying to reach is

<a id="ZoomGallery" href="/uploads/products/892_3521-05 .jpg" class="MagicZoomPlus"   title="Franklin Paradigm Grey Sofa"><img src="/uploads/products/892_3521-05 .jpg" alt="FranklinParadigm Grey Sofa" /></a>
Karthik VU
  • 561
  • 5
  • 17
Matty2Shoes
  • 11
  • 1
  • 7
  • The var element isn't image but the link. You can get the image like below : http://stackoverflow.com/questions/10381296/best-way-to-get-child-nodes, and get attribute from that node. – Weenesta - Mathieu Dormeval Mar 22 '17 at 14:39

3 Answers3

2

Your .innerHTML() is not needed. The getAttribute() function simply returns a string with the value of the attribute, or null if the attribute is non-existent.

To get the src of your element, therefore, the url of your image, you'd have to do :

var imageSrc = element.getAttribute("src");

and then simply return imageSrc

More info on the mozilla developper network

jac
  • 51
  • 7
  • Ok so when I try using the new line it returns "null" I know I'm missing something. function() { var element = document.getElementsByClassName("MagicZoomPlus")[0]; var imageSrc = element.getAttribute("src"); return imageSrc; } – Matty2Shoes Mar 22 '17 at 14:53
  • your tag doesn't have the class name you are looking for (Magic zoom plus). You are selecting the anchor tag here, when you want to be selecting the img tag to get its src. – jac Mar 22 '17 at 14:57
1

You could use a selector instead, and also you can access the attribute directly with the dot notation. If you are trying to target the image within the link:

function(){
    var image = document.querySelector(".MagicZoomPlus > img");
    // get
    console.log(image.src);
    // or set the image source
    image.src = "https://example.com/hello.jpg";
    return image;
}
Philippe
  • 1,169
  • 12
  • 14
0

This is what I ended up coming up with, which works.

function myFunc() {
  var img = document.querySelector(".MagicZoomPlus img");

  return img.src
}
Matty2Shoes
  • 11
  • 1
  • 7