Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
Detect questions and answer in rich text and add class using JS

I would like to automatically add an FAQ schema depending on the content of a div with id #content in a webpage.

I'm not a developper, I'm building in webflow and learning on the go whenever I need a script.

So far, this is where I got:

var questions = document.getElementsByClassName("auto-question");
var answer = document.getElementsByClassName("auto-answer");
var schema ={
    "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": []
}
for (var i = 0; i<questions.length; i++){
    var new_schema =
    {
    "@type": "Question",
    "name": questions[i].innerText,
    "acceptedAnswer": {
      "@type": "Answer",
      "text": answer[i].innerText
    }
  }
  
  schema.mainEntity.push(new_schema);
}
var script = document.createElement('script');
script.type = "application/ld+json";
script.text = JSON.stringify(schema);
document.querySelector('body').appendChild(script);

It works but now my issue is that I want to add the class .auto-question and .auto-answer automatically.

This is an example of the page I'm trying to work on: crédit impôt recherche.

My idea is the following process:

  1. for each H2 title ending with question mark
  2. add class .auto-question to H2
  3. add class .auto-answer to innerText until next H2 or until end of #content if none

Again, I'm not a developper, putting bits of code together is fine but writing my own is out of my league.

Hope you can help, Thanks a lot

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your approach is good in general, but I don't think it's appropriate in this case. It won't work like that, because it doesn't fit the given HTML structure, it needs to be adapted to that structure.

As all elements are siblings, one approach would be to get all elements in the FAQ container, and then loop through each element, and use H2 tag as an indicator for constructing a question schema. Adding extra classes would be pointless, as you'd need to add class to every element...

So, upon reading an H2 tag, construct a schema, push it to the FAQs, until done.

Here's the code, replace your FAQ code with this one:

window.addEventListener('DOMContentLoaded', () => {

    // setup selectors
    const snippetsContainer = '.w-richtext';
    const questionIndicatorTag = 'H2';

    // get the faq container and all nodes
    const faqHTML = Array.from(document.querySelector(snippetsContainer).children);

    const schemaFAQ = {
        "@context": "https://schema.org",
        "@type": "FAQPage",
        "mainEntity": []
    };


    // data variables to store while looping
    let questionName = answerText = '';

    // loop each element, h2 is a question indicator, other nodes are its answer
    faqHTML.forEach((el, i) => {

        // check question tag indicator
        if (el.tagName === questionIndicatorTag) {

            // new question, add previous question to the faqs, reset
            // check if index indicates it's not the first question
            if (i > 0) {
                // add to the FAQ
                schemaFAQ.mainEntity.push({
                    "@type": "Question",
                    "name": questionName,
                    "acceptedAnswer": {
                        "@type": "Answer",
                        "text": answerText
                    }
                });
                // reset data
                questionName = answerText = ''
            }
            // new question
            questionName = el.innerText;
        } else {
            // add answer
            answerText += el.innerText + '<br>';
        }
        // all done
        if (i + 1 === faqHTML.length) {
            schemaFAQ.mainEntity.push({
                "@type": "Question",
                "name": questionName,
                "acceptedAnswer": {
                    "@type": "Answer",
                    "text": answerText
                }
            });
        }
    });

    // insert
    const scriptFAQ = document.createElement('script');
    scriptFAQ.type = "application/ld+json";
    scriptFAQ.text = JSON.stringify(schemaFAQ);
    document.getElementsByTagName('head')[0].appendChild(scriptFAQ);

});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda