Advertisements
I am using the following JavaScript to filter table contents (all columns), but I am facing a few issues:
1- I want to add an array for letters so it shows some words with "French accent marks" (e = ë, è, é, ê)
– (c = ç)
.. etc.
2- How to ignore inner html tags, like "href, hidden link, styles.. etc", as now when I filter for href, or .com (in the html code) it shows as a results.
3- Is it possible to ignore a whole column? (If I have like 5 columns, can I ignore column 3 for example with all its content?
The following is the current working code:
const myFunction = () => {
const trs = document.querySelectorAll('#myTable tr:not(.header)')
const filter = document.querySelector('#myInput').value
const regex = new RegExp(filter, 'i')
const isFoundInTds = td => regex.test(td.innerHTML)
const isFound = childrenArr => childrenArr.some(isFoundInTds)
const setTrStyleDisplay = ({ style, children }) => {
style.display = isFound([
...children // <-- All columns
]) ? '' : 'none'
}
trs.forEach(setTrStyleDisplay)
}
<input
type="text"
id="myInput"
onkeyup="myFunction()"
placeholder="search.."
title="search">
<br>
<div align="center">
<table border="1" id="myTable" >
<tr>
<td>cédille</td>
<td><a href="google.com">book</a></td>
</tr>
<tr>
<td>Le tréma</td>
<td>accent </td>
</tr>
<tr>
<td>garçon </td>
<td>accept</td>
</tr>
</table>
</div>
>Solution :
-
You can remove the accents from the content before searching
-
Use
innerText
instead ofinnerHTML
-
Filter out the unwanted column indices
const removeAccents = str => str.normalize("NFD").replace(/\p{Diacritic}/gu, "");
const myFunction = () => {
const trs = document.querySelectorAll('#myTable tr:not(.header)')
const filter = document.querySelector('#myInput').value
const regex = new RegExp(filter, 'i')
const isFoundInTds = td => regex.test(removeAccents(td.innerText))
const isFound = childrenArr => childrenArr.some(isFoundInTds)
const setTrStyleDisplay = ({ style, children }) => {
style.display = isFound(
[...children].filter((_, i) => i !== 2) // <-- All columns except the 3rd (index 2)
) ? '' : 'none'
}
trs.forEach(setTrStyleDisplay)
}
<input
type="text"
id="myInput"
onkeyup="myFunction()"
placeholder="search.."
title="search">
<br>
<div align="center">
<table border="1" id="myTable" >
<tr>
<td>cédille</td>
<td><a href="google.com">book</a></td>
<td>ignored</td>
<td>included</td>
</tr>
<tr>
<td>Le tréma</td>
<td>accent </td>
<td>ignored1</td>
<td>included1</td>
</tr>
<tr>
<td>garçon </td>
<td>accept</td>
<td>ignored2</td>
<td>included2</td>
</tr>
</table>
</div>
Also, in the future, post your questions separately