The first file is 'faq-contents.html'
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="faq-classification">
</div>
<script src="faq-contents.js"></script>
</body>
</html>
linked "faq-contents.js" file.
const faqContents = [
{order: "00",
question: "Our mission",
answer: "our mission answer"
},
{order:"01",
question: "How does Linstock work?",
answer: "it works well"
},
]
const faqCenter = document.querySelector(".faq-classification")
const questionClicked = document.querySelectorAll("#faq-question")
window.addEventListener("DOMContentLoaded", function() {
});
questionClicked.forEach(function(click){
click.addEventListener("click", function(e) {
const questionsAndAnswer = e.currentTarget.dataset.order;
const restoredFaq = faqContents.filter(function(faqItem){
if(faqItem.order === questionsAndAnswer) {
let result =
`<section id="faq-section">
<div class="faq-classification">
</div>
<div class="faq-main-contents">
<h3 class="faq-question-title">
"${faqItem.question}"
</h3>
<p class="faq-answer-conntents">
"${faqItem.answer}"
</p>
</div>
</section>`
faqCenter.innerHTML = result
return result;
}
})
})
})
Here is another code file related to the issue.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Frequently Asked Questions(FAQ)</title>
</head>
<body>
<section id="faq" class="faq">
<div class="faq-category">
<div class="faq-contents">
<h2>About Linstock</h2>
<p id="faq-question" data-order="00"><a href="#faq-contents.html">Our mission</a></p>
<p id="faq-question" data-order="01"> How does Linstock work?</p>
</div>
</div>
</section>
<script src="faq-contents.js"></script>
</body>
</html>
I would like to show objects of Q&A restored in const faqContets
in case that the string "Our mission" in third file is clicked.
I tried to show the contents with faqCenter.innerHTML = result
but innerHTML property is null.
How do I fix it?
To solve your first problem, innerHTML property is null, look at the document the js can access:
faq-contents.js is loaded in both html files and adds the click eventlistener to every #faq-question.
For faq-contents.html, it does have .faq-classifications, BUT no #faq-question => the forEach is executed 0 times, resulting in no eventlisteners added thus not doing anything.
For index.html, it has #faq-question twice, so clicking fires it (duh). BUT: this page does not have .faq-classifications => faqCenter = null
Other mentions for your code:
window.addEventListener("DOMContentLoaded", function() { });
<= don't close it directly, put some code inside of the {}, otherwise it is useless. Probably you put the });
to high in the file by accident.
skip the filter and return stuff and use forEach or something similar, as you are already getting the result out by faqCenter.innerHTML = result