9

Is it possible the read the price using the javascript

<span id="product_price_00873">
<span itemprop="price">178.00</span>
</span>

I just want to price 178.00. I can only using javascript.

Any suggestions will be appreciated.

jbcedge
  • 18,965
  • 28
  • 68
  • 89

3 Answers3

22

If you have the product element in product and you're using a modern browser, this should work:

var price = product.querySelector('[itemprop=price]').textContent;
icktoofay
  • 126,289
  • 21
  • 250
  • 231
12

Update:

Use Element.querySelector as described in icktoofay's answer, or perform the following:

const els = [...document.getElementsByTagName('span')];
props = els.filter(x => !!x.getAttribute('itemprop'));

// print the first element's price
console.log(props.shift().innerHTML)

Original:

var els = document.getElementsByTagName('span'), i = 0, price;

for(i; i < els.length; i++) {
    prop = els[i].getAttribute('itemprop');

    if(prop) {
        price = els[i].innerHTML;
        break;
    }
}
Alex
  • 34,899
  • 5
  • 77
  • 90
0

The problem with complex websites and metadata is that meta tags not always have the itemprop attribute. And in some case they have itemprop only but not a name attribute.

With this script you can get all the Meta with an itemprop attribute and print its content.

  const allMeta = document.getElementsByTagName("meta");
    
  for (let i = 0; i < allMeta .length; i++) {
      if( allMeta [i].getAttribute("itemprop") != null){
        console.log( allMeta [i].getAttribute("itemprop")+":"+allMeta [i].getAttribute('content') );
      }
  }