Warm tip: This article is reproduced from serverfault.com, please click

Creating and querying elements in a new DOM body

发布于 2021-01-16 00:17:02

I have the following code in my typescript file:

    let body = document.body;
    // let body = document.body.cloneNode(true);

    body.querySelectorAll('button').forEach(b => {

        b.removeAttribute('click.delegate');
    });

I am trying to update and query the body of a dom page to make a new html document, but when I do this it updates the current one as well as the one I am building on the fly. The cloneNode prevents me from using querySelectorAll(). Any ideas? Thanks for you help.

Questioner
cdub
Viewed
0
pilchard 2021-01-16 08:34:08

You can programmatically create a new body element using document.createElement() and assign the innerHTML of the active document.body to it.

let body = document.createElement('body');
body.innerHTML = document.body.innerHTML;

body.querySelectorAll('div').forEach(d => {
  d.classList.add('red');
  console.log(d)  
});
.red {
  background-color:tomato;
}
<body>
  <div>
    <button type='button'>Button</button>
  </div>
</body>