简体   繁体   中英

Javascript: Get ID of all Elements in a Section

I have a Script that maps all Elements starting with a specific ID:

var mirror = [...document.querySelectorAll('[id^="abc_"]')].map(elm => elm.id);

Now i need a function, that not all of the IDs are mapped, but just those in the section "foo"

<section id="foo">
  <div id="abc_1></div>
  <a id="abc_2"></a>
</section>

<section id="bar">
  <div id="abc_3></div>
  <a id="abc_4"></a>
</section>

With the obove function i get abc_1, abc_2, abc_3, abc_4. But i need only the IDs in section "foo" (abc_1 and abc_2)

Is there a way?

 var mirror = [...document.querySelectorAll('section#foo [id^="abc_"]')].map(elm => elm.id); console.log(mirror)
 <section id="foo"> <div id="abc_1">link1</div> <a id="abc_2">link2</a> </section> <section id="bar"> <div id="abc_3">link3</div> <a id="abc_4">link4</a> </section>

try this

var mirror = [...document.querySelectorAll('section#foo [id^="abc_"]')].map(elm => elm.id);

You can do this easily. Just pass the section id #foo in the .querySelectorAll() like:

 document.querySelectorAll('#foo [id^="abc_"]')

This will find all the ids which start with abc_ inside the #foo section only, instead of all sections.

 var mirror = [...document.querySelectorAll('#foo [id^="abc_"]')].map(elm => elm.id); console.log( mirror )
 <section id="foo"> <div id="abc_1"></div> <a id="abc_2"></a> </section> <section id="bar"> <div id="abc_3"></div> <a id="abc_4"></a> </section>

Just add another selector at the beginning section#foo

 let mirror = [...document.querySelectorAll('section#foo [id^="abc_"]')].map(ele => ele.id); console.log(mirror);
 <section id="foo"> <div id="abc_1"></div> <a id="abc_2"></a> </section> <section id="bar"> <div id="abc_3"></div> <a id="abc_4"></a> </section>

you can use as @Pain said but to be general without "section"

 var mirror = [...document.querySelectorAll('#foo [id^="abc_"]')].map(elm => elm.id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM