我有以下示例代码。我正在尝试在javascript代码中添加一些类到id="section"
但不成功。错误:删除注释代码时无法读取null的属性'classList'。任何帮助将不胜感激!
第1部分:
var template = document.querySelector('#container').innerHTML;
var contents = '';
var section = document.createElement("div");
// These two lines cause the error
var section = document.getElementById("section");
section.classList.add("bg-yellow");
contents = template.replace(/\{\{title\}\}/, "Title");
section.insertAdjacentHTML('beforeend', contents);
document.getElementById('content').appendChild(section);
第2部分:(从Randy Casburn的原始答案更新)
var data = [{
"Title": "One"},
{"Title": "Two"},
{"Title": "Three"}];
var template = document.querySelector('#container').innerHTML;
var contents = '';
var section = document.createElement("div");
for(var i = 0; i < data.length; i++){
contents += template.replace(/\{\{title\}\}/, data[i].Title);
}
section.innerHTML = contents;
var innerSection = section.querySelector("#section");
innerSection.classList.add("bg-yellow","blue");
document.getElementById('content').appendChild(section);
.sub-section{
background: tomato;
width: 100px;
}
.bg-yellow{
background: yellow!important;
width: 100%;
height: auto;
}
.blue{
color: blue!important;
}
<div id="content"></div>
<script type="template" id="container">
<div id="section">
<div class="sub-section">
<h1>{{title}}</h1>
</div>
</div>
</script>
这很容易实现。创建div
并将其innerHTML
设置为模板内容。然后将div
添加到DOM。
你是在正确的轨道上,但只是跳过了一个重要的步骤。
var data = [{
"Title": "One"},
{"Title": "Two"},
{"Title": "Three"}];
var template = document.querySelector('#container').innerHTML;
var contents = '';
for(var i = 0; i < data.length; i++){
contents += template.replace(/\{\{title\}\}/, data[i].Title);
}
//var contents = template.replace(/\{\{title\}\}/, "Title");;
var section = document.createElement("div");
section.innerHTML = contents;
var innerSection = section.querySelectorAll(".section");
innerSection.forEach(el=>el.classList.add("bg-yellow"));
document.getElementById('content').appendChild(section);
.sub-section {
background: tomato;
width: 100px;
}
.bg-yellow {
background: yellow!important;
width: 100%;
height: auto;
}
<div id="content"></div>
<script type="template" id="container">
<div class="section">
<div class="sub-section">
<h1>{{title}}</h1>
</div>
</div>
</script>
编辑:OP更改了问题中的用例,因此更新答案以反映新问题: - /
如果您在脚本标记(或浏览器可以理解的其他脚本语言)中指定Javascript以外的内容类型,则浏览器不会对其进行解释,您只能以纯文本格式访问它。
参考(How does HTML tags work inside script tag?)
你没有放在脚本中的html DOM,但是你试图查询它。