jbcedge
jbcedge

Reputation: 19505

using javascript to read value from itemprop

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.

Upvotes: 11

Views: 17846

Answers (3)

Tommaso Lintrami
Tommaso Lintrami

Reputation: 26

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') );
      }
  }

Upvotes: 0

Alex
Alex

Reputation: 35409

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;
    }
}

Upvotes: 12

icktoofay
icktoofay

Reputation: 129001

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;

Upvotes: 24

Related Questions