Javascript 在所选元素中搜索字符串并隐藏包含该字符串的 html 标签

Javascript search for string in selected elements and hide the html tag that contains that string

我写了一个简单的 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';

您可能还需要更好的函数名称。