I have the following sample codes. I'm trying to add some class to the id="section"
inside the javascript code but unsuccessful. Error: Cannot read property 'classList' of null when removing the commented codes. Any helps would be greatly appreciated!
Part 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);
Part 2: (Updated from Randy Casburn's orig answer)
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>