javascriptdomdocumentfragment

make a DOM element's content be the one of a document fragment


I am trying to insert into a DOM element the content of a document fragment (in pure javascript). The working principle is this:

var a = document.getElementById("a"),
    b = document.getElementById("b");

now i place the content of "a" into a document fragment, using a template element

var content = document.createElement("template");
content.innerHTML = a.innerHTML;
content = content.content.cloneNode(true);

now i would like to replace the content of b with the content of content. I tried with a simple b.innerHTML = content.innerHTML;, but it seems like if document fragments doesn't have innerHTML property.
Is this possible to do?

Note: i know this is totally an ineffective way to do the task of making b.innerHTML = a.innerHTML, but obviously this is just a simplification of a bigger task i am managing to do.


Solution

  • You need to create "clones" and by using the template content property you can then use the innerHTML of a and b into your fragments.

    Example:

    const a = document.getElementById("a"),
      b = document.getElementById("b");
    
    // note template will only be parsed, to render it use js...
    
    function initTemplate() {
    
      const container = document.getElementById("container");
      const template = document.getElementById("t");
    
      // create a first clone with the innerHTML of a...
    
      const firstClone = template.content.cloneNode(true);
      firstClone.textContent = a.innerHTML;
    
      // create a second clone with the innerHTML of b...
    
      const secondClone = template.content.cloneNode(true);
      secondClone.textContent = b.innerHTML;
    
      // append to the document
    
      container.appendChild(firstClone);
      container.appendChild(secondClone);
    
    
    }
    <p id="a">Paragraph A</p>
    <p id="b">Paragraph B</p>
    <button onclick="initTemplate()">Init Template</button>
    
    <br>
    <div id="container"></div>
    
    <template id="t">
      
    </template>

    If you want to check if your browser supports the HTML template element, do something like this:

    if ("content" in document.createElement("template") {
    
       // clone the elements as above and append them to the document
    
    }
    

    Mozilla Docs and Mozilla Docs