I am trying to clone a template in a header using the Node.cloneNode()
without success.
Here is my markup
var header = document.querySelector("header"),
$templateHeader = document.querySelector("[data-template=header]");
header.innerHTML = $templateHeader.innerHTML;
<header></header>
<!--templates-->
<template data-template=header>
<div class=container>
<menu class=row>
<li><a>Home</a></li>
<li><a>items</a></li>
<li><a>Reseller</a></li>
<li><a>Shop</a></li>
</menu>
</div>
</template>
This works just fine
header.innerHTML = $templateHeader.innerHTML;
while this will not work
var header = document.querySelector("header"),
$templateHeader = document.querySelector("[data-template=header]");
header.innerHTML = $templateHeader.cloneNode(true);
<header></header>
<!--templates-->
<template data-template=header>
<div class=container>
<menu class=row>
<li><a>Home</a></li>
<li><a>items</a></li>
<li><a>Reseller</a></li>
<li><a>Shop</a></li>
</menu>
</div>
</template>
even this
var header = document.querySelector("header"),
$templateHeader = document.querySelector("[data-template=header]");
header.appendChild($templateHeader.cloneNode(true));
<header></header>
<!--templates-->
<template data-template=header>
<div class=container>
<menu class=row>
<li><a>Home</a></li>
<li><a>items</a></li>
<li><a>Reseller</a></li>
<li><a>Shop</a></li>
</menu>
</div>
</template>
when i console.log $templateHeader.cloneNode(true)
this is what i get
Can anyone help me understanding what i am doing wrong here?
Note: i don't want to use jquery
regards, Tambo
You have cloned the entire template and are trying to append the template to your header. You don't want to do that, you want to append the content of the template.
var header = document.querySelector("header"),
$templateHeader = document.querySelector("[data-template=header]");
header.appendChild($templateHeader.content.cloneNode(true));
<header></header>
<!--templates-->
<template data-template=header>
<div class=container>
<menu class=row>
<li><a>Home</a></li>
<li><a>items</a></li>
<li><a>Reseller</a></li>
<li><a>Shop</a></li>
</menu>
</div>
</template>
That said, in a number of samples I found online, I found importNode
used instead of cloneNode
:
var clone = document.importNode(t.content, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With