javascript 如何通过类名获取嵌套 div 中的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14983425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:03:44  来源:igfitidea点击:

How to get an element inside nested divs by class name?

javascript

提问by Haz

A webpage with HTML looks like this:

带有 HTML 的网页如下所示:

<div id="Parent-div" > </div>
<div class="first-child-div"> </div>
<div class=" second-child-div"> 
    <div class="first-grand-child"> </div>
    <div class="second-grand-child"> </div>
    <div class="Third-grand-child"> 
        <div class="Grand-grand child"> 
           <button  class="Confirm-button">Confirm!</button> 
        </div>
    </div>
</div>

I've Tried This code using greasemonkey to remove a button from the div with the class named "Grand-grand child"

我已经尝试过使用greasemonkey从带有名为“Grand-grand child”的类的div中删除一个按钮的代码

This is what I did:

这就是我所做的:

var targetDiv = document.querySelector("#<Parent-div>. Grand-grand.child");

targetDiv.innerHTML = "Hello world!";

The Button wasn't replaced by the Hello world! text, What did I do wrong?

Button 没有被 Hello world 取代!文字,我做错了什么?

回答by PeeHaa

document.querySelector('.Grand.grand.child');

Demo: http://jsfiddle.net/yGv3v/

演示:http: //jsfiddle.net/yGv3v/

回答by Alex Williams

You should change <div class=" Grand grand child">to <div class="Grand-grand-child">and then you can select it with $('.Grand-grand-child').

您应该更改<div class=" Grand grand child"><div class="Grand-grand-child">,然后您可以使用 选择它$('.Grand-grand-child')

Edit

编辑

If you want to use pure JavaScript, then you can select the node element via

如果你想使用纯 JavaScript,那么你可以通过以下方式选择节点元素

var grandChildChildNode = document.getElementsByClassName('Third')[0].children[0]

This should work in sufficiently modern browsers.

这应该在足够现代的浏览器中工作。