在Javascript中查找元素

在Javascript中查找元素,javascript,jquery,Javascript,Jquery,我需要找到一个类为“kinder”且元素为“a”的div。我需要从a获取并提醒href属性 更新的示例:例如。如果我有: <div class="controls-wrapper"> <div class="title" role="contentinfo"> <header> <div class="kinder" aria-hidden="true"> <

我需要找到一个类为“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>

您的帖子用jQuery标记。以下是jQuery的实现方法:

alert( $('.kinder a').prop('href') );
或香草JavaScript:

alert ( document.querySelectorAll('.kinder a')[0].href );

您可以通过Jquery使用
attr
函数获得它,如下所示:

Jquery:

alert($('.kinder a').attr('href'));

问候

问题:

  • javascript方法返回具有所有给定类名的所有子元素的类似数组的对象,因此您必须通过索引将要使用的对象作为目标(例如获取第一次使用
    aUserVideo[0]

  • 如果要获取属性,应使用
    getAttribute()
    而不是
    attribute

  • 建议的解决方案:

    alert($('.kinder a').attr('href'));
    
    您只需使用
    querySelector
    获取href即可。href
    类似:

    document.querySelector(".kinder a").href
    
    希望这有帮助

    window.addEventListener(“DOMContentLoaded”,function()){
    console.log(document.querySelector(“.kinder a”).href);
    },假)
    
    getElementsByClassName
    返回一个类似于前面答案的objectDupe的数组。我得到的是“未定义”您是否在使用jquery?如果div没有锚标记,这将不起作用。关于这是否可能,问题有点模糊。这是真的,OP说我需要找到一个类为“kinder”的div,它有一个元素“a”,所以我们只需要在
    .kinder
    中获取锚。我没有定义。你的HTML结构与OP中发布的相同吗?querySelector是否返回数组?如果是的话,根据这个答案,href将是未定义的。我得到了未定义的