Dynamic Structured Data FAQ Schema Builder

If you're building a FAQ page for your website, you should take advantage of Google's rich snippets with FAQ structured data.

But who's got the time to write your questions and answers on both your page and in your FAQ structured data?

We can make this a lot quicker, by adding a script to your page, and some small modifications to your HTML.

When you're done, a script with type "ld+json" will be added to your page.

Be sure to test the code with Google's rich results test tool.

FAQ Page rich results on Google search engine.

/**
 * Dynamically build ld json schema for a FAQ.
 * Wrap your question/answer areas with a data-qa attribute.
 * Wrap the question with data-question.
 * Wrap the answer with data-answer.
 *
 * A ld json script tag element with a FAQPage type will be created dynamically
 * and appended to your page head.
 *
 * @author  Nick Adams - Arcane Web Design
 * @license  MIT
 */
function buildLdJsonScriptElement() {
    let ldJsonScriptElement = document.createElement("script");
    ldJsonScriptElement.setAttribute("type", "application/ld+json");
    let o = {
        "@context": "https://schema.org",
        "@type": "FAQPage",
        "mainEntity": []
    };
    const qas = document.querySelectorAll("[data-qa]");
    qas.forEach((qa) => {
        const q = qa.querySelector("[data-question]").innerText;
        const a = qa.querySelector("[data-answer]").innerText;
        addQuestion(o, q, a);
    });
    ldJsonScriptElement.innerText = JSON.stringify(o);
    return ldJsonScriptElement;
}
function addQuestion(o, question, answer) {
    o.mainEntity.push({
    "@type": "Question",
        "name": question,
        "acceptedAnswer": {
            "@type": "Answer",
            "text": answer
        }
    })
}
document.head.append(buildLdJsonScriptElement());

We have more for you!

We have a constantly growing list of tools, packages, and dev tutorials/articles!

We're also active on Twitter/X. Follow/chat with us. We love making friends with other devs and designers!