如何使用 javascript 循环遍历每个具有特定类的 div?

时间:2021-07-28 18:35:25

标签: javascript html css for-loop

我正在尝试搜索常见问题解答页面,该页面将隐藏没有用户输入的关键字的结果。现在搜索仅突出显示关键字,我为每个问题分配了 div,类别为“faq” -问题”。因此,我尝试使用“faq-question”类遍历每个 div,检测用户搜索的关键字是否存在(这些关键字已分配标签“mark”),然后如果 div="faq- question" 中包含 <mark> 标签。我的代码现在突出显示所有 divs="faq-question" 而不是那些里面有 <mark> 的。我该如何解决这个问题?

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");
    }
}

编辑:<mark> 标签是一个动态值。问题与循环有关,但要清楚:例如,您在 <input id="keywords"> 中输入“lorem”。然后html会变成

<h4>What is <mark>Lorem</mark> Ipsum?</h4>

...等等。因此,在这种情况下,我只使用 <mark> 标记来检测 div 是否具有与用户搜索的任何内容匹配的关键字

2 个答案:

答案 0 :(得分:1)

只是简单的拼错。您将变量声明为问题,因此在 for 循环内部应该是 questions 而不是 question

所以代码将是

<input type="text" id="keywords" placeholder="Search on the page..."></input>
<div class="faq-question"><h4>What is <mark>Lorem Ipsum?<mark></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>

    var questions = document.getElementsByClassName("faq-question");


    for(x = 0; x < questions.length; x++) {
    if(questions[x].getElementsByTagName('mark').length){
        questions[x].style.backgroundColor = "#FFFF00";
        console.log("shown");
    } else {
        questions[x].style.backgroundColor = "#FFFFFF";
        console.log("hidden");
    }
}

答案 1 :(得分:0)

选择所有问题,检查该元素是否作为子元素存在,如果存在,则切换一个类。

document.querySelectorAll(".faq-question").forEach(function(elem) {
  const hasMarks = elem.querySelectorAll("mark").length > 0;
  elem.classList.toggle("hasMatch", hasMarks);
});
.hasMatch {
  background-color: lime;
}
<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 <mark>fact</mark> that a reader will be distracted by the readable content of a page when looking at its layout.</p>
</div>

相关问题