[英]Javascript: Get ID of all Elements in a Section
I have a Script that maps all Elements starting with a specific ID:我有一个脚本,它映射以特定 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"现在我需要一个 function,不是所有的 ID 都被映射,而只是“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.使用上面的 function 我得到 abc_1、abc_2、abc_3、abc_4。 But i need only the IDs in section "foo" (abc_1 and abc_2)但我只需要“foo”部分中的 ID(abc_1 和 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:只需在.querySelectorAll()
中传递部分 id #foo
,例如:
document.querySelectorAll('#foo [id^="abc_"]')
This will find all the ids which start with abc_
inside the #foo
section only, instead of all sections.这将仅在#foo
部分中找到所有以abc_
开头的 id,而不是所有部分。
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只需在开头部分添加另一个选择器#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"你可以像@Pain所说的那样使用,但一般来说没有“部分”
var mirror = [...document.querySelectorAll('#foo [id^="abc_"]')].map(elm => elm.id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.