2

I wrote a simple javascript code to find whether the string exists in innerHtml in selected elements, now I would like to hide element that contains that string but I'm not sure how to get the tag id or something to hide specified element. Here's my code.

 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();
4

1 回答 1

3

您可以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';

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

于 2018-11-16T16:59:53.600 回答