将HTML文本插入到之前使用JavaScript创建的div中

时间:2019-03-29 10:28:47

标签: javascript html

我正在单张地图中创建弹出窗口。弹出内容应使用javascript动态创建。在使用innerHTML将内容添加到弹出框内的div容器时,出现错误消息:“无法将属性'innerHTML'设置为null”

这是我的代码:

//create div for form element "Baumpatenschaft"
var div_baumpatenschaft = document.createElement('div');

//add div_baumpatenschaft to DOM (child of <div> with id="formular")
formular.appendChild(div_baumpatenschaft);

//create ID for div
div_baumpatenschaft.id = "div_baumpatenschaft";

var pt = document.getElementById("div_baumpatenschaft");    

//HTML code for creating radio buttons stored in var baumpatenschaft
var baumpatenschaft = 
      '<label for="radio_ja">ja</label><br/>\
      <input checked="checked" type="radio" name="baumpatenschaft" id="radio_ja" value="ja"/>\
      <label for="radio_nein">nein</label><br/>\
      <input type="radio" name="baumpatenschaft" id="radio_nein" value="nein"/>';


//adding the HTML-code to div_baumpatenschaft
pt.innerHTML = baumpatenschaft;

显然,尚未创建div_baumpatenschaft,因为innerHTML尝试将HTML代码插入<div>内。

我也尝试过element.insertAdjacentHTML(),但有相同的错误。

我在做什么错? 还有另一种可能性可以解决该问题?我当然想用document.createElement('div')创建div,并且我还想将单选按钮定义为存储在变量中的HTML文本,而不是用document.createElement('input')来定义,这是我之前所做的。

1 个答案:

答案 0 :(得分:3)

这是因为 创建的元素 不属于文档的一部分。您可以按以下方式访问之前,将 创建的元素 附加到 body 中:

document.body.appendChild(div_baumpatenschaft);

//create div for form element "Baumpatenschaft"
var div_baumpatenschaft = document.createElement('div');

//create ID for div
div_baumpatenschaft.id = "div_baumpatenschaft";

document.body.appendChild(div_baumpatenschaft);

var pt = document.getElementById("div_baumpatenschaft");    

//HTML code for creating radio buttons stored in var baumpatenschaft
var baumpatenschaft = 
      '<label for="radio_ja">ja</label><br/>\
      <input checked="checked" type="radio" name="baumpatenschaft" id="radio_ja" value="ja"/>\
      <label for="radio_nein">nein</label><br/>\
      <input type="radio" name="baumpatenschaft" id="radio_nein" value="nein"/>';


//adding the HTML-code to div_baumpatenschaft
pt.innerHTML = baumpatenschaft;

更新

//create div for form element "Baumpatenschaft"
var div_baumpatenschaft = document.createElement('div');

//add div_baumpatenschaft to DOM (child of <div> with id="formular")
var formular = document.getElementById('formular');
formular.appendChild(div_baumpatenschaft);

//create ID for div
div_baumpatenschaft.id = "div_baumpatenschaft";

var pt = document.getElementById("div_baumpatenschaft");    

//HTML code for creating radio buttons stored in var baumpatenschaft
var baumpatenschaft = 
      '<label for="radio_ja">ja</label><br/>\
      <input checked="checked" type="radio" name="baumpatenschaft" id="radio_ja" value="ja"/>\
      <label for="radio_nein">nein</label><br/>\
      <input type="radio" name="baumpatenschaft" id="radio_nein" value="nein"/>';


//adding the HTML-code to div_baumpatenschaft
pt.innerHTML = baumpatenschaft;
<div id="formular"></div>