admin管理员组文章数量:1394611
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?
3 Answers
Reset to default 4You have a couple of options:
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
.You can use
document.getElementById
to get thediv
, and then usequerySelector
orgetElementsByTagName
on that element (rather thandocument
) 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 thegetElementsByTagName
version, since what you get is anHTMLCollection
, 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
本文标签: javascriptFind children of children elements with getElementByIdStack Overflow
版权声明:本文标题:javascript - Find children of children elements with getElementById - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744096296a2590344.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论