Search code examples
javascripthtmldom-manipulation

How can I create a search feature for an array of divs with no text content?


Is there a way to create a search filter for HTML elements based on their values, IDs, or names etc. the same way you can create a search filter based on the elements text content? Here is my search filter for divs with text content. Is there a way to implement the search filter if the divs have no text content? Am I able to access the elements tag and use that somehow?

Javascript filter based on text content

let input = document.querySelector(`#input`);
let animalDivs = document.querySelectorAll(`.animal`);

input.addEventListener(`keyup`, function(e) {
  const term = e.target.value.toLowerCase();
  animalDivs.forEach(function(div) {
    const animal = div.textContent.toLocaleLowerCase();
    if (animal.includes(term)) {
      div.style.display = "block"
    } else {
      div.style.display = "none"
    }
  });
});
<input type="text" id="input">
<div class="container">
  <div id="monkey" class="animal">The Monkey</div>
  <div id="mongoose" class="animal">The Mongoose</div>
  <div id="mouse" class="animal">The Mouse</div>
  <div id="moose" class="animal">The Moose</div>
</div>


Solution

  • You can use data attributes

    tag is not a recommended/known tag attribute

    Also slow down on the template literals. I choose to use input event listener too since it handles paste

    let input = document.getElementById('input');
    let animalDivs = document.querySelectorAll('.animal');
    
    input.addEventListener('input', function(e) {
      const term = this.value.toLowerCase();
      animalDivs.forEach(function(div) {
        const animal = div.dataset.tag.toLocaleLowerCase();
        div.hidden = !animal.includes(term)
      });
    });
    <input type="text" id="input" autocomplete="off">
    <div class="container">
      <div data-tag="The Monkey" id="monkey" class="animal">The Monkey</div>
      <div data-tag="The Mongoose" id="mongoose" class="animal">The Mongoose</div>
      <div data-tag="The Mouse" id="mouse" class="animal">The Mouse</div>
      <div data-tag="The Moose" id="moose" class="animal">The Moose</div>
    </div>