2017-04-20 6 views
1

JavaScriptで動的に<template>要素を作成し、<h1>要素を子要素として追加し、テンプレートの内容を複製してからテンプレートを文書本体に追加しようとしています。テンプレートから内容を取得できない

テンプレートのcontentプロパティにアクセスするときに問題が発生するのは、単に#document-fragmentです。ここで

コードです:

var temp = document.createElement('template'); 
var h1 = document.createElement('h1'); 
h1.textContent = 'hello'; 

var div = document.createElement('div').appendChild(h1) 
temp.appendChild(div) 

console.log('temp: ', temp) 
console.log('temp content: ', temp.content) 

var c = document.importNode(temp.content, true) 
document.body.appendChild(c) 

そして、ここではconsole.log'sための出力です:

Template output

私はここで間違って何をしているのですか?テンプレートの内容が空白になっているのはなぜですか?

+2

'appendChild'関数が親(' div')ではなく子要素( 'h1')を返すため、' div'は "削除されました"。 – Titus

+0

@ティトスああ。私は 'div'に子を追加していると思って、' div'が返されました。それを指摘してくれてありがとう。 – Graham

答えて

2

あなたが<template>を作成するときは、(ドキュメント・ある).contentプロパティに、ではない要素自体に(appendChild()付き)DOMのコンテンツを追加する必要があります。

var temp = document.createElement('template'); 
 
var h1 = document.createElement('h1'); 
 
h1.textContent = 'hello'; 
 

 
var div = document.createElement('div') 
 
div.appendChild(h1) 
 

 
//append DOM to .content 
 
temp.content.appendChild(div) 
 

 
console.log('temp: ', temp) 
 
console.log('temp content: ', temp.content) 
 

 
var c = document.importNode(temp.content, true) 
 
document.body.appendChild(c)

代替はinnerHTMLプロパティを使用してHTML文字列を追加することです。

temp.innerHTML = '<div><h1>Hello</h1></div>' 
0

注:は、h1divではなく、h1に変数を設定します。 What is the behavior of document.createElement when passed as an argument?を参照してください。

セット<template>.innerHTMLdiv要素の.outerHTMLに、パラメータとしてtemp.contentdocument.bodyに連鎖.appendChild()を呼び出します。

window.onload = function() { 
 

 
    var temp = document.createElement('template'); 
 
    var h1 = document.createElement('h1'); 
 
    h1.textContent = 'hello'; 
 

 
    var div = document.createElement('div'); 
 
    div.appendChild(h1); 
 
    temp.innerHTML = div.outerHTML; 
 

 
    console.log('temp: ', temp.content); 
 

 
    document.body.appendChild(temp.content); 
 

 
}
<body></body>

関連する問題