Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Define the class for your questions and answers here.
- // They should be marked up in a consistent manner.
- var parentClass = 'faq_block'
- var questionClass = 'faq_question';
- var answerClass = 'faq_answer';
- // Output schema to console. Set to `false` if adding via tag manager.
- var logOutput = true;
- (function(){
- var parent = document.querySelector('.' + parentClass.replace('.', ''))
- // Build Data
- var questions = Array.from(parent.querySelectorAll('.' + questionClass.replace('.', ''))).map(function(e){return e.textContent});
- var answers = Array.from(parent.querySelectorAll('.' + answerClass.replace('.', ''))).map(function(e){return e.textContent});
- if (questions.length && answers.length){
- var data = {
- "@context": "https://schema.org",
- "@type": "FAQPage",
- "mainEntity": []
- };
- buildItem = (q,a) => {
- var item = {
- "@type": "Question",
- "name": null ,
- "acceptedAnswer": {
- "@type": "Answer",
- "text":null }
- };
- item['name'] = q;
- item['acceptedAnswer']['text'] = a;
- return item;
- }
- console.assert(questions.length == answers.length, {questions: questions.length, answers: answers.length, errorMsg: "Questions and Answers are not the same lengths"});
- data['mainEntity'] = questions.map(function(q,i){return buildItem(q,answers[i])});
- var script = document.createElement('script');
- script.type = "application/ld+json";
- script.innerHTML = JSON.stringify(data);
- document.getElementsByTagName('head')[0].appendChild(script);
- if (logOutput){
- console.log(script.outerHTML);
- }
- }
- })(document);
Add Comment
Please, Sign In to add comment