jroakes

faqPage

May 4th, 2020 (edited)
600
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Define the class for your questions and answers here.
  2. // They should be marked up in a consistent manner.
  3. var parentClass   = 'faq_block'
  4. var questionClass = 'faq_question';
  5. var answerClass   = 'faq_answer';
  6.  
  7. // Output schema to console. Set to `false` if adding via tag manager.
  8. var logOutput     = true;
  9.  
  10. (function(){
  11.  
  12.     var parent = document.querySelector('.' + parentClass.replace('.', ''))
  13.  
  14.     // Build Data
  15.     var questions = Array.from(parent.querySelectorAll('.' + questionClass.replace('.', ''))).map(function(e){return e.textContent});
  16.     var answers = Array.from(parent.querySelectorAll('.' + answerClass.replace('.', ''))).map(function(e){return e.textContent});
  17.  
  18.     if (questions.length && answers.length){
  19.  
  20.         var data = {
  21.           "@context": "https://schema.org",
  22.           "@type": "FAQPage",
  23.           "mainEntity": []
  24.         };
  25.  
  26.         buildItem = (q,a) => {
  27.  
  28.             var item = {
  29.                 "@type": "Question",
  30.                 "name": null ,
  31.                 "acceptedAnswer": {
  32.                   "@type": "Answer",
  33.                   "text":null }
  34.                 };
  35.  
  36.             item['name'] = q;
  37.             item['acceptedAnswer']['text'] = a;
  38.  
  39.             return item;
  40.         }
  41.    
  42.         console.assert(questions.length == answers.length, {questions: questions.length, answers: answers.length, errorMsg: "Questions and Answers are not the same lengths"});
  43.  
  44.         data['mainEntity'] = questions.map(function(q,i){return buildItem(q,answers[i])});
  45.  
  46.         var script = document.createElement('script');
  47.         script.type = "application/ld+json";
  48.         script.innerHTML = JSON.stringify(data);
  49.         document.getElementsByTagName('head')[0].appendChild(script);
  50.  
  51.         if (logOutput){
  52.             console.log(script.outerHTML);
  53.         }
  54.  
  55.     }
  56.  
  57. })(document);
RAW Paste Data