How do I search something in html css js?

Asked

Viewed 194 times

1

So Guys, I wanted to be able to search for items in html, without a bank, because the items will not be added dynamically, they will already be pre-established, as I am a beginner I have no idea how to do this, if anyone can help me I thank you from now on.

ul{
list-style: none;
}
<input type="text" placeholder="Pesquise aqui">
<ul>
<li>Abacate</li>
<li>Banana</li>
<li>Cenoura</li>
<li>Tomate</li>
</ul>

1 answer

1

There it is. The logic is simple: every time a key is pressed inside the input, the Javascript code generates a regular expression with the value of input, expression that is compared to the text of each item in the list. Items whose text does not correspond to it receive display: none; in your css, so that they remain hidden. The ones that match, are with display: block;

Obs: the script only works to find items that BEGIN with what was typed. "Green apple", for example, would not be found just by typing the word "green".

const campoPesquisa = document.querySelector('#pesquisa');
const items = document.querySelectorAll('#lista li');
let regexCheck;

campoPesquisa.addEventListener('keyup', function(e) {
  regexCheck = new RegExp(`^${e.target.value}`, 'i');  
  items.forEach(item => {
    if (!item.innerText.match(regexCheck)) {
      item.style.display = 'none';
    } else {
      item.style.display = 'block';
    }
  });
});
#lista {
  list-style: none;
  }
<input type="text" id="pesquisa" placeholder="Pesquise aqui">
<ul id="lista">
  <li>Abacate</li>
  <li>Banana</li>
  <li>Cenoura</li>
  <li>Tomate</li>
</ul>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.