Currently, I have a function that allows me to search for HTML elements based on text content:
function findElementsByText(text: string): HTMLElement[] {
const selectors = 'button'
// This conditional statement ensures that an empty text query doesn't match all elements on the page
const pattern = new RegExp(text === '' ? '^$' : text)
return Array.from(document.querySelectorAll(selectors)).filter(
(element) => element.innerText.match(pattern)
)
}
I decided to broaden the search by incorporating anchor tags into the selection criteria:
const selectors = 'a, button'
However, this modification triggered a TypeScript error:
The error message states: 'Type 'Element[]' is not assignable to type 'HTMLElement[]'. Type 'Element' is missing various properties from type 'HTMLElement': accessKey, accessKeyLabel, autocapitalize, dir, and more.
Why did including another selector cause this issue, and what steps can be taken to resolve it?
To examine the live code example, please refer to the following link:
https://codesandbox.io/s/typescript-selectors-yhu1j1?fontsize=14&hidenavigation=1&theme=dark