我有一个包含多个div的页面,每个div都包含一个带有特定文本的h1,我想要做的是添加一个输入字段,并且用户将基于该文本在该输入字段上键入所有内容除与搜索查询匹配的行外,其他行将消失(即使查询不是100%与h1字符串匹配,搜索也应能够选择父div。
这是该代码的示例,因此,如果某人键入“ Disodium”或“ Glutamate”,则应选择“ row-1”。
<div class="col">
<div class="row-1">
<h1>Disodium/Sodium Cocoyl Glutamate</h1>
</div>
<div class="row-2">
<h1>Cetearyl Glucoside – Zuckeremulgator</h1>
</div>
<div class="row-3">
<h1>Chamomilla Recutita (Matricaria) Flower Extract – Kamille Extrakt</h1>
</div>
<div class="row-4">
<h1>Citral – Bestandteil von Zitronengrasöl</h1>
</div>
</div>
答案 0 :(得分:0)
您可以映射每个孩子并找出它是否包含搜索查询 并根据我的喜好改变背景颜色
const q = "Glutamate";
const col = document.querySelector('.col');
// Array.from(col.children) this method will produce an iterable array you can map through each child
Array.from(col.children).map(child =>{
//hiding all others
if(child.querySelector('h1').innerText.indexOf(q) === -1){
child.style.display = "none";
}else{
// do what ever you want
child.style.display = "block";
// iam changing the background color to yellow
child.style.backgroundColor = "#ffff00";
}
})
<div class="col">
<div class="row-1">
<h1>Disodium/Sodium Cocoyl Glutamate</h1>
</div>
<div class="row-2">
<h1>Cetearyl Glucoside – Zuckeremulgator</h1>
</div>
<div class="row-3">
<h1>Chamomilla Recutita (Matricaria) Flower Extract – Kamille Extrakt</h1>
</div>
<div class="row-4">
<h1>Citral – Bestandteil von Zitronengrasöl</h1>
</div>
</div>