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

Time:02-15

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 >
  <div id="monkey" >The Monkey</div>
  <div id="mongoose" >The Mongoose</div>
  <div id="mouse" >The Mouse</div>
  <div id="moose" >The Moose</div>
</div>

CodePudding user response:

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 >
  <div data-tag="The Monkey" id="monkey" >The Monkey</div>
  <div data-tag="The Mongoose" id="mongoose" >The Mongoose</div>
  <div data-tag="The Mouse" id="mouse" >The Mouse</div>
  <div data-tag="The Moose" id="moose" >The Moose</div>
</div>

  • Related