Home > Software engineering >  Is there a special context for the deep parameter in the importNode function?
Is there a special context for the deep parameter in the importNode function?

Time:11-13

I came across the importNode function for the first time yesterday and I don't understand the deep parameter. The Mozilla documentation says:

A boolean flag, whose default value is false, which controls whether to include the entire DOM subtree of the externalNode in the import. If deep is set to true, then externalNode and all of its descendants are copied. If deep is set to false, then only externalNode is imported - the new node has no children.

https://developer.mozilla.org/en-US/docs/Web/API/Document/importNode?retiredLocale=de

If I try and set the deep parameter to true it works and the whole parent element is copied. But if I set the deep parameter to false nothing happens. Here is the moment that I realize that I haven't really understood the documentation here. Why do I need the deep = false?

const btn1 = document.querySelector(".deep-true");
const btn2 = document.querySelector(".deep-false");
btn1.addEventListener("click", appendElement_1.bind())
btn2.addEventListener("click", appendElement_2.bind())

function appendElement_1() {
  const parent = document.querySelector("div .parent");
  const node = document.importNode(parent, true);
  document.body.appendChild(node);
}

function appendElement_2() {
  const parent = document.querySelector("div .parent");
  const node = document.importNode(parent, false);
  document.body.appendChild(node);
}
span {
  color: green;
}
.parent {
  background: green;
  height:20px;
  border: 1px solid red;
}
<div id="app">
  
  <div >
    <div >
      <p>hello <span>World</span></p>
      <h1>Bye</h1>      
    </div>

  </div>

  <button >ImportNode (deep: true)</button>
  <button >ImportNode (deep: false)</button>
</div>

CodePudding user response:

Just to illustrate the deep argument and how the selected node is used a slightly modified version of the original code that simply adds the outerHTML to a textarea so that it is apparent what is happening.

const d=document;

const evthandler=(e)=>{
  d.querySelector('textarea').innerHTML=d.importNode( d.querySelector("div#app .parent"), parseInt( e.target.dataset.deep ) ).outerHTML
}

d.querySelector(".deep-true").addEventListener("click", evthandler )
d.querySelector(".deep-false").addEventListener("click", evthandler )
span {
  color: green;
}
<div id="app">
  <div >PARENT
    <div >CHILD
      <p>hello <span>World</span></p>
      <h1>Bye</h1>      
    </div>
  </div>
  <button data-deep=1 >ImportNode (deep: true)</button>
  <button data-deep=0 >ImportNode (deep: false)</button>
</div>

<textarea cols=50 rows=6></textarea>

  • Related