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

javascript - Find children of children elements with getElementById - Stack Overflow

programmeradmin10浏览0评论

I've to edit the content and attributes of the table. This DOM is provided by a third-party tool and I use JavaScript to edit different parts.

<div id="myId">
  <div>
    <div>
      <table>Content I have to edit</table>
    </div>
  </div>
</div>

I've to edit the content and attributes of the table. This DOM is provided by a third-party tool and I use JavaScript to edit different parts.

<div id="myId">
  <div>
    <div>
      <table>Content I have to edit</table>
    </div>
  </div>
</div>

I've tried to use document.getElementById('myId').children, but how can I edit attributes of childrens children?

Share Improve this question asked Aug 5, 2019 at 14:45 JonasJonas 1115 silver badges14 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

You have a couple of options:

  1. You can use document.querySelector to find the table:

    var table = document.querySelector("#myId table");
    

    document.querySelector takes any valid CSS selector and returns the first match, so the selector is #myId table.

  2. You can use document.getElementById to get the div, and then use querySelector or getElementsByTagName on that element (rather than document) to find the table:

    var div = document.getElementById("myId");
    var table = div.querySelector("table");
    // Or: var table = div.getElementsByTagName("table")[0];
    

    (Note the [0] on the getElementsByTagName version, since what you get is an HTMLCollection, not just one element.)

MDN's DOM material is quite good. (More generally, its coverage of web technologies is quite good.)

Assuming for whatever reason you can't directly select the table [1], then you can chain .children[0], or better yet firstElementChild, calls.

let table = document.getElementById('myId').firstElementChild.firstElementChild.firstElementChild;

console.log(table);
<div id="myId">
  <div>
    <div>
      <table>Content I have to edit</table>
    </div>
  </div>
</div>

[1] If you can, then querySelector as in T.J.'s answer would be easier to maintain.

firstElementChild Property returns a DOM Object where you can use the same firstElementChild property. Look at the docmumentation:

https://www.w3schools./jsref/prop_element_firstelementchild.asp

or if you need a specific item and it is not the first, you need to use the children property:

document.getElementById("myId").children[2].children[2]

https://www.w3schools./jsref/prop_element_children.asp

发布评论

评论列表(0)

  1. 暂无评论