Javascript在选定元素中搜索字符串并隐藏包含该字符串的html标记
我编写了一个简单的javascript代码来查找字符串是否存在于选定元素的innerHtml中,现在我想隐藏包含该字符串的元素,但我不确定如何获取标记id或隐藏指定元素的内容。这是我的密码Javascript在选定元素中搜索字符串并隐藏包含该字符串的html标记,javascript,html,htmlcollection,Javascript,Html,Htmlcollection,我编写了一个简单的javascript代码来查找字符串是否存在于选定元素的innerHtml中,现在我想隐藏包含该字符串的元素,但我不确定如何获取标记id或隐藏指定元素的内容。这是我的密码 function hideTemplateOption(collToHide, hideText) { let collection = document.getElementsByClassName("product_tr_cus"); if(collectionContains(coll
function hideTemplateOption(collToHide, hideText) {
let collection = document.getElementsByClassName("product_tr_cus");
if(collectionContains(collection,"test")) {
console.log("contains");
} else {
console.log("nope");
}
}
function collectionContains(collection, searchText) {
for (var i = 0; i < collection.length; i++) {
if( collection[i].innerText.toLowerCase().indexOf(searchText) > -1 ) {
return true;
}
}
return false;
}
hideTemplateOption();
函数hideTemplateOption(collToHide,hideText){
let collection=document.getElementsByClassName(“product_tr_cus”);
if(集合包含(集合,“测试”)){
控制台日志(“包含”);
}否则{
控制台日志(“nope”);
}
}
函数collectionContains(集合、搜索文本){
对于(变量i=0;i-1){
返回true;
}
}
返回false;
}
hideTemplateOption();
您可以执行收集[i].style.display='none'代码>或更好地有条件地设置它:
功能切换(集合、搜索文本){
var=false;
对于(变量i=0;i
Foo
酒吧
- Baz
- Quux
在你的集合包含的函数中,你手头有元素(集合[i]
),所以你可以直接添加到它的类列表中。你的解决方案隐藏了给定集合中的所有元素,即使我给集合[i]@WinithePooh sorry没有测试这个,检查更新,你需要使用匹配,我认为indexOf
仅适用于数组,我从未见过它与字符串一起使用。我解决了我的问题,我将所有带有product\u tru\cus的div放在一个具有相同类名的大div中。解决方案是首先选择集合,然后选择该集合中具有给定类的所有元素