I am currently working on creating a search functionality for an FAQ page that will filter out results that do not contain the keywords entered by the user. Right now, the search function only highlights the keywords, and I have assigned divs with the class "faq-question" for each question. My goal is to iterate through each div with the class "faq-question", check if the searched keyword (marked with the "mark" tag) is present, and then change the background color of that section accordingly. However, my current code is highlighting all the divs with the class "faq-question" instead of just those containing the <mark>
tag. How can I resolve this issue?
HTML
<input type="text" id="keywords" placeholder="Search on the page..."></input>
<div class="faq-question"><h4>What is Lorem Ipsum?</h4>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.<p></div>
<div class="faq-question"><h4>Why do we use it?</h4>
<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.</p></div>
Javascript:
//Hide unrelated search results
var question = document.getElementsByClassName("faq-question");
var keyword = document.querySelector("mark");
for(x = 0; x < question.length; x++) {
if(typeof(keyword) != 'undefined' && keyword != null){
question[x].style.backgroundColor = "#FFFF00";
console.log("shown");
} else {
question[x].style.backgroundColor = "#FFFFFF";
console.log("hidden");
}
}
Edit: The <mark>
tag is a dynamic value. To clarify, if you enter "lorem" in the
<input id="keywords">
, the HTML will change to
<h4>What is <mark>Lorem</mark> Ipsum?</h4>
...and so forth. In this case, I am using the <mark>
tag to determine if the div contains the matching keywords that the user searched for.