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?

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

本文标签: javascriptFind children of children elements with getElementByIdStack Overflow