Skip to content

Instantly share code, notes, and snippets.

@Scemist
Last active October 14, 2022 18:16
Show Gist options
  • Save Scemist/b4079095b5931278d49547e3f29fb736 to your computer and use it in GitHub Desktop.
Save Scemist/b4079095b5931278d49547e3f29fb736 to your computer and use it in GitHub Desktop.
JavaScript Table Filter Rows By Key Search v3.0
// Called by the input search element: onkeyup="pesquisar()"
const pesquisar = (keyWord, tableKey = 'table') => {
const
oldBody = document.querySelector(`${tableKey} tbody`),
keyWord = keyRaw.toUpperCase(),
newBody = oldBody.cloneNode(true)
for (let row of newBody.children) {
row.style.display = row.innerText.toUpperCase().includes(keyWord)
? ''
: 'none'
}
oldBody.replaceWith(newBody)
}
@Scemist
Copy link
Author

Scemist commented Oct 14, 2022

Old Version - v2.0

In large scale, have a too bad performance, because it renderizes for each row

// Called by the input search element: onkeyup="pesquisar()"

const pesquisar = (keyWord, tableKey) => {
	const
		tabela = document.querySelector(tableKey),
		linhas = tabela.querySelectorAll('tr')

	for (let linha of linhas) {
		linha.style.display = 'none'

		for (let coluna of linha.querySelectorAll('td')) {
			const txtValor = coluna.textContent || coluna.innerText

			if (txtValor.toUpperCase().indexOf(keyWord.toUpperCase()) > -1)
				linha.style.display = 'table-row'
		}
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment