Skip to content

Instantly share code, notes, and snippets.

@neodigm
Last active March 11, 2023 00:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neodigm/4f4e3b40a433f7af15f46ec769436604 to your computer and use it in GitHub Desktop.
Save neodigm/4f4e3b40a433f7af15f46ec769436604 to your computer and use it in GitHub Desktop.
Generate JSON-LD FAQ derived from existing HTML
// This snippet when executed in the browser will log a valid JSON-LD FAQ rich snippet
// derived from the existing HTML FAQ.
// www.theScottKrause.com
const jOut = {"@context": "https://schema.org", "@type": "FAQPage","mainEntity": []}
const aelQs = [ ... document.querySelectorAll(".l-faq") ]
aelQs.forEach(function( elFAQ ){
let elQ = elFAQ.querySelector("summary")
let elA = elFAQ.querySelector("p")
let oOut = {"@type": "Question", "name": "##Q##", "acceptedAnswer": {"@type": "Answer", "text": "##A##" }}
oOut.name = elQ.textContent
oOut.acceptedAnswer.text = elA.textContent
jOut.mainEntity.push( oOut )
})
console.warn( JSON.stringify( jOut ) )
@neodigm
Copy link
Author

neodigm commented Mar 11, 2023

Sorry, this script had a bug in which it was only capturing the first question. It has been fixed, tested, and verified.
Each question is expected to be contained in a SECTION element, that element has a class = l-faq.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment