最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get an element inside nested divs by class name? - Stack Overflow

programmeradmin2浏览0评论

A webpage with HTML looks like this:

<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"

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?

A webpage with HTML looks like this:

<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"

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?

Share Improve this question edited Feb 20, 2013 at 16:32 Haz asked Feb 20, 2013 at 15:19 HazHaz 1121 gold badge2 silver badges8 bronze badges 6
  • 2 Note: class="Grand grand child" means the element will have 2 classes namely grand and child. Not one class named Grand grand child – techfoobar Commented Feb 20, 2013 at 15:21
  • @techfoobar: I'm using greasemonkey to edit some page with the same example above, probably, they are 2 classes – Haz Commented Feb 20, 2013 at 15:28
  • @j08691: I have tried getelementsbyclassname and querySelector with no result – Haz Commented Feb 20, 2013 at 15:30
  • If its greasemonkey, you can safely use document.querySelector as in PeeHaa's answer. – techfoobar Commented Feb 20, 2013 at 15:30
  • @ techfoobar: Tried that already with no luck – Haz Commented Feb 20, 2013 at 15:41
 |  Show 1 more comment

2 Answers 2

Reset to default 16
document.querySelector('.Grand.grand.child');

Demo: 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').

Edit

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

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

This should work in sufficiently modern browsers.

发布评论

评论列表(0)

  1. 暂无评论