skip to Main Content

Assuming a screen element has been selected using something like const foo = document.getElementById("foo") I’d like to retrieve all markup between that elements tags <div id="foo">...</div>

The issue I find is it only returns me one level in the dom tree. Is there a way to retrieve all markup? ie. for <div id="foo"> <ul><li>item1</li><li>item2</li></ul></div>

2

Answers


  1. try this code:
    const foo = document.getElementById("foo");
    const markup = foo.outerHTML;
    I hope this helps!

    Login or Signup to reply.
  2. I’m not sure, why you’re saying outerHTML only returns the first child.
    Providing a snippet below showing it returns the entire dom structure including the queried element.

    const parent = document.querySelector("#parent");
    
    const requiredDomTree = parent.outerHTML;
    console.log(requiredDomTree)
    <div id="parent">
      <ul>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li>1</li>
        <li><span>deep nested</span></li>
      </ul>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search