gpt4 book ai didi

javascript - 在 Javascript 中查找元素

转载 作者:行者123 更新时间:2023-11-29 16:46:05 25 4
gpt4 key购买 nike

我需要找到一个类为“kinder”且有一个元素“a”的div。我需要从 a 获取并提醒 href 属性。

更新的例子:例如。如果我有:

<div class="controls-wrapper">
<div class="title" role="contentinfo">
<header>
<div class="kinder" aria-hidden="true">
<a tabindex="-1" href="https://google.com" target="_blank">
<img src="https://imageUrl/120x120.jpg" alt="" width="60" height="60">
</a>
</div>

我需要提醒“http://google.com

我试过下面的代码:

var aUserVideo = document.getElementsByClassName('kinder')

aUserVideoHref = aUserVideo.attribute("a");
aUserVideoHref = aUserVideoHref.attribute("href");

alert(aUserVideoHref);

最佳答案

问题:

  1. javascript 方法 getElementsByClassName() 返回具有所有给定类名的所有子元素的类似数组的对象,因此您必须通过索引定位要使用的对象(例如获取第一个使用 aUserVideo[0] ).

  2. 如果您想获取一个属性,您应该使用 getAttribute() 而不是 attribute

建议的解决方案:

您可以使用 querySelector.href 简单地获取 href,例如:

document.querySelector(".kinder a").href

希望这对您有所帮助。

window.addEventListener("DOMContentLoaded", function() {
console.log(document.querySelector(".kinder a").href);
}, false);
<div class="kinder" aria-hidden="true"> <a tabindex="-1" href="http://google.com" target="_blank"> <img src="https://imageUrl/120x120.jpg" alt="" width="60" height="60"> </a> </div>

关于javascript - 在 Javascript 中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41349748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com