在你的查詢選擇器中,你使用的模式 ([0-9]+
) 沒有被解釋為正則表達(dá)式。使用 RegExp 構(gòu)造函數(shù)從字符串創(chuàng)建一個(gè)正則表達(dá)式對(duì)象:
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>