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

666 views Asked by At

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

There are 1 answers

3
jcubic On BEST ANSWER

You can do collection[i].style.display = 'none'; or better set it conditionally:

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>

it will hide the node that have the string if you want the opposite then use:

collection[i].style.display = item_found ? '' : 'none';

and you probably will need better name for the function as well.