-3 javascript arrays href
我试图创建一个数组,使用javascript 在main元素中保存所有href。现在我不是程序员,但我想我会尝试通过以下两种方法之一来实现:
a)隔离主要元素(document.getElementsByTagName(“ main”)),然后尝试从该对象中提取所有href。
b) Create an array of all href's on the page (document.links) and then check for every href whether it has main as a parent node.
So far I haven't found a solution for either approach. Can anyone help me with a code fragment that creates an array with all href's within main? Thanks a lot in advance. I already spent hours figuring it out myself xl
Example HTML:
<main>
<div id="content">
<div class="classA">
<a href="/pagePathA/"></a>
</div>
<div class="classB">
<a href="/pagePathB/"></a>
</div>
</div>
</main>
Run Code Online (Sandbox Code Playgroud)
use querySelectorAll
let hrefs = [...document.querySelectorAll('main a[href]')].map(({href}) => href);
console.log(hrefs);Run Code Online (Sandbox Code Playgroud)
<main>
<a href="#1">1</a>
<a href="#2">2</a>
<div>
<a href="#3">3</a>
</div>
</main>Run Code Online (Sandbox Code Playgroud)
If you want only children of main, not all descendants
let hrefs = [...document.querySelectorAll('main>a[href]')].map(({href}) => href);
console.log(hrefs);Run Code Online (Sandbox Code Playgroud)
<main>
<a href="#1">1</a>
<a href="#2">2</a>
<div>
<a href="#3">3</a>
</div>
</main>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43 次 |
| 最近记录: |