-2

Using this view-page-source has my reference http://www.ebest.cl/audifonos-alta-fidelidad-house-of-marley-revolution.html

I am trying to return the "3355" from this div using Javascript.

  1. I want return this in the Chrome developer tools console first.

document.getElementsByClassName("data-product-id");

When I execute this I return an empty array. []

  1. I want to be able to return this in a google tag manager variable. I write the code once I can at least test and return it in the console.

Thanks! Spencer

Spencer Gallardo
  • 75
  • 1
  • 1
  • 6
  • that is definitely not a class name – Daniel Cheung Aug 27 '15 at 13:45
  • A possible duplication of http://stackoverflow.com/questions/9496427/can-i-get-elements-by-attribute-selector-when-queryselectorall-is-not-available – Daniel Cheung Aug 27 '15 at 13:47
  • [getElementsByClassName](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) does not return an array. It returns a [HTMLCollection](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection), a array-like object. It is an important distinction. In addition to the other reasons array-like objects are not the same as arrays, HTMLCollections in particular are different in that they are a *live collection*. If the DOM changes the content of your collection might change even *after* you queried for it! – Useless Code Aug 28 '15 at 07:07

1 Answers1

0

It's a data-* attribute, not a className. I went through the trouble of finding the child that has that data-attribute instead of directly referencing the correct node, since I (and possibly you) have no idea if the yotpo bottomline class will be available every time, so I put more faith in the product-shop className being available. If there are multiple products on the page, you'll only get the first ID. Extending to all ID's is trivial.

var productID = Array.prototype.slice.call(
        document.getElementsByClassName('product-shop')[0].childNodes
    ).reduce(function (acc, child) {
        var att = (child.nodeName === 'DIV') ? child.getAttribute('data-product-id') : false;
        if (att) acc = att;
        return acc;
    }, '');
Shilly
  • 8,511
  • 1
  • 18
  • 24