简体   繁体   English

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

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

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从div中删除一个名为“Grand-grand child”的按钮

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! 按钮没有被Hello世界取代! text, What did I do wrong? 文字,我做错了什么?

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

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

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,则可以选择节点元素via

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

This should work in sufficiently modern browsers. 这应该适用于足够现代的浏览器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM