首页 > 解决方案 > 我如何通过 1 个 className 获取元素的所有 att“href”?js

问题描述

例如,我有代码:

<a class="link" href="https://example1.com">example1</a>
<a class="link" href="https://example2.com">example2</a>
<a class="link" href="https://example3.com">example3</a>

需要使用类“链接”获取元素的所有属性“href”示例输出:

https://example1.com
https://example2.com
https://example3.com

我有脚本,但它总是得到第一个元素:

let i = 0;
let b = 3;
while (i < 3) { 
var href = $('.link').attr('href');
  console.log(href);
  i++;
}

我如何在下一个元素处切换?

标签: javascriptjqueryweb

解决方案


那是因为您一直选择相同的元素。您可以先获取所有项目并将它们存储在一个数组中。然后你可以使用一个循环来遍历你的数组并对所有的链接做一些事情。

这是我在 JavaScript 中的做法:

let links = document.getElementsByClassName("link");

for (let i = 0; i > links; i++) {
  let href = links[i].getAttribute("href");
  console.log(href);
}
<a class="link" href="https://example1.com">example1</a>
<a class="link" href="https://example2.com">example2</a>
<a class="link" href="https://example3.com">example3</a>


推荐阅读