Pascalus
Pascalus

Reputation: 35

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?

Upvotes: 2

Views: 896

Answers (4)

Boub Thr
Boub Thr

Reputation: 11

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

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

Upvotes: 1

Ankit
Ankit

Reputation: 632

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>

Upvotes: 1

palaѕн
palaѕн

Reputation: 73926

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>

Upvotes: 1

Marik Ishtar
Marik Ishtar

Reputation: 3049

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);

Upvotes: 1

Related Questions