mercredi 1 décembre 2021

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




Aucun commentaire:

Enregistrer un commentaire