Skip to content

Instantly share code, notes, and snippets.

@Blazing-Mike
Created May 12, 2025 10:22
Show Gist options
  • Save Blazing-Mike/4f175ea809384943ea81ba779fc7ae22 to your computer and use it in GitHub Desktop.
Save Blazing-Mike/4f175ea809384943ea81ba779fc7ae22 to your computer and use it in GitHub Desktop.
document.addEventListener('DOMContentLoaded', function() {
// 1. Find all FAQ item containers
const faqItems = document.querySelectorAll('.faq-item'); // Use the class you defined
// 2. Check if any FAQs were found
if (faqItems.length > 0) {
// 3. Prepare the basic structure for FAQPage schema
const faqSchema = {
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": [] // This array will hold all our questions and answers
};
// 4. Loop through each found FAQ item
faqItems.forEach(item => {
// Find the question and answer elements WITHIN the current item
const questionElement = item.querySelector('.faq-question'); // Use the class for the question
const answerElement = item.querySelector('.faq-answer'); // Use the class for the answer container
// Ensure both question and answer elements exist and have content
if (questionElement && answerElement && questionElement.textContent.trim() && answerElement.textContent.trim()) {
// 5. Create the Question schema object
const questionObj = {
"@type": "Question",
"name": questionElement.textContent.trim(), // Get the text content of the question
"acceptedAnswer": {
"@type": "Answer",
"text": answerElement.innerHTML.trim() // Use innerHTML to preserve simple formatting (like <p>, <a>, <strong>) or use textContent if only plain text is needed. Trim whitespace.
}
};
// 6. Add the question object to the mainEntity array
faqSchema.mainEntity.push(questionObj);
} else {
console.warn('Skipping FAQ item due to missing question or answer:', item);
}
});
// 7. Check if we actually collected any valid Q&A pairs
if (faqSchema.mainEntity.length > 0) {
// 8. Create the <script> tag
const scriptTag = document.createElement('script');
scriptTag.type = 'application/ld+json';
// 9. Convert the JavaScript object to a JSON string and assign it
scriptTag.textContent = JSON.stringify(faqSchema, null, 2); // null, 2 adds pretty-printing (optional)
// 10. Append the script tag to the <head> of the document
document.head.appendChild(scriptTag);
}
} else {
console.log('No FAQ items found on the page to generate schema.');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment