P粉2376476452023-08-31 10:23:22
In your query selector, you are using a pattern ([0-9]
) that is not interpreted as a regular expression. Create a regular expression object from a string using the RegExp constructor:
const regex = new RegExp('^a[0-9]+-[a-zA-Z]+$'); const parentElement = document.querySelector('#parent-element'); const items = parentElement.querySelectorAll(`[id]`); const children = Array.from(items).filter(item => regex.test(item.id)); console.log(children);
<div id="parent-element"> <p id="a1-a">Child 1</p> <p id="a1-b">Child 2</p> <p id="INVALID-1">Child 3</p> <p id="a10-f">Child 4</p> <p id="INVALID-2">Child 5</p> <p id="b1-a">Child 6</p> <p id="a1-2">Child 7</p> </div>