我编写了一个简单的javascript代码,以查找该字符串是否存在于选定元素的innerHtml中,现在我想隐藏包含该字符串的元素,但是我不确定如何获取标签ID或某些东西来隐藏指定的元素。这是我的代码。
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();
您可以collection[i].style.display = 'none';
有条件地做或更好地设置它:
function toggle(collection, searchText) {
var found = false;
for (var i = 0; i < collection.length; i++) {
var item_found = collection[i].innerText.toLowerCase().match(searchText);
collection[i].style.display = item_found ? '' : 'none';
if (item_found) {
found = true;
}
}
return found;
}
let collection = document.getElementsByClassName("product_tr_cus");
document.querySelector('input').addEventListener('keyup', function(event) {
toggle(collection, event.target.value);
});
<input/>
<ul>
<li class="product_tr_cus">Foo</li>
<li class="product_tr_cus">Bar</li>
<li class="product_tr_cus">Baz</li>
<li class="product_tr_cus">Quux</li>
</ul>
如果想要相反的话,它将隐藏具有字符串的节点,然后使用:
collection[i].style.display = item_found ? '' : 'none';
并且您可能还需要为该函数使用更好的名称。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句