Is there a way to access JSON-LD via JavaScript if it doesn't have an ID? Is there a way to access JSON-LD via JavaScript if it doesn't have an ID? json json

Is there a way to access JSON-LD via JavaScript if it doesn't have an ID?


You can get all JSON-LD blocks with

 document.querySelectorAll('script[type="application/ld+json"]');

or just the first one with

document.querySelector('script[type="application/ld+json"]');

Here's a full example:

var jsonld = JSON.parse(document.querySelector('script[type="application/ld+json"]').innerText);document.getElementById('result').innerText = jsonld.endDate;
<html>  <head>    <script type="application/ld+json">      {        "@context": "http://schema.org",        "@type": "Event",        "name": "A random event",        "startDate": "2013-09-14T21:30",        "endDate": "2013-09-14T21:30"      }    </script>  </head>  <body>    <p>The end date is: <strong id="result"></strong></p>  </body></html>