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