javascript - 我如何通过 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++;
}
我如何在下一个元素处切换?
解决方案
那是因为您一直选择相同的元素。您可以先获取所有项目并将它们存储在一个数组中。然后你可以使用一个循环来遍历你的数组并对所有的链接做一些事情。
这是我在 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>
推荐阅读
- r - 每日死亡的热图动画
- python - 无法加载图标 plyer 库
- javascript - 如何在 Java Script 中重构 EventListener 函数
- unit-testing - 简单的 Mokito 示例
- graph-theory - Sagemath Graph Theory:is_perfect() 返回 false,即使团数和色数相等
- batch-file - 用于重命名文件夹中文件的批处理命令
- c++ - 请帮我解决一个简单的 c++ std::time_t 问题
- asynchronous - 我可以在 GCP 云函数中使用 python - aiohttp 吗?
- f# - 为什么代码的匹配版本不能在 F# 中编译
- c++ - 将代码转换为 C++ 时,如何使用具有 typedef 枚举的 C 标头?