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>