Use regular expressions to match id values
P粉757556355
P粉757556355 2023-08-30 16:13:18
0
1
579
<p>I want to find all child nodes of the <code>g</code> node whose value is <code>id</code> and the attribute consists of: </p> <pre class="brush:php;toolbar:false;">a[number]-[one or more characters] // example: // - id="a1-a" // - id="a1-b" // - id="a1-abcd" // - id="a10-f" // - id="a0-z" // - id="b1-a" // Illegal // - id="a1-2" // Illegal</pre> <p>So I tried: </p> <pre class="lang-js prettyprint-override"><code>const items = gElement.querySelectorAll(`[id^='a[0-9] -[a-zA-Z] ']`) </code></pre> <p>However, it doesn't work. </p>
P粉757556355
P粉757556355

reply all(1)
P粉237647645

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template