Reputation: 23154
Html code:
<body>
<template id="hello">
<div>Hellow world!</div>
</template>
<script src="x.js"></script>
</body>
Typescript code:
function greeter(person: string) {
return "hello " + person
}
var user = "Jane"
var greetNode = document.createElement("p")
greetNode.innerHTML = greeter(user)
document.body.appendChild(greetNode)
var node = document.importNode(
document.querySelector("#hello").firstChild, true
)
document.body.appendChild(node)
Error from chrome:
Uncaught TypeError: Failed to execute 'importNode' on 'Document': parameter 1 is not of type 'Node'.
Expected behavior is that the "hello world" div should be added to the html body.
The jsfiddle:
https://jsfiddle.net/kindlychung/4o2fwwfb/
Any suggestions?
Upvotes: 0
Views: 97
Reputation: 3516
Content inside of template
tag is not rendered, it is not actually in the document. The line document.querySelector("#hello").firstChild
is returning null
, hence the error.
In order to access template's inner HTML you can use its content
attribute. Here you can read the following:
There is also a content attribute, which is read-only and provides access to the template's contents.
So the code would be:
function greeter(person: string) {
return "hello " + person
}
var user = "Jane"
var greetNode = document.createElement("p")
greetNode.innerHTML = greeter(user)
document.body.appendChild(greetNode)
var template = document.querySelector("#hello")
var div = template.content.querySelector("div")
var node = document.importNode(div, true)
document.body.appendChild(node)
Upvotes: 1