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 10, 2022

Old Version - v1.0

Only works with 1 column

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

const pesquisar = _ => {
	const tabela = document.querySelector("table")
	const tr = tabela.getElementsByTagName("tr")
	const input = document.querySelector("#pesquisa")
	let filtro = input.value.toUpperCase()
	let td, controle, txtValor

	for (controle = 0; controle < tr.length; controle++) {
		td = tr[controle].getElementsByTagName("td")[2] // 3° Column
		
		if (td) {
			txtValor = td.textContent || td.innerText
			
			if (txtValor.toUpperCase().indexOf(filtro) > -1)
				tr[controle].style.display = ""
			else
				tr[controle].style.display = "none"
		}
	}
}

@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