0

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>

10
  • Are you saying the error occurs when you uncomment those lines? Commented Jan 18, 2019 at 15:31
  • @MTCoster yes, that's right Commented Jan 18, 2019 at 15:33
  • 1
    The browser ignores everything inside the <script type="template" /> block. Thus you can not query it before adding it to the DOM properly. You read it, yet never add it to the DOM. Commented Jan 18, 2019 at 15:33
  • You cannot put html inside script tags Commented Jan 18, 2019 at 15:34
  • 1
    You can put whatever you want inside script tags, however the browser interpret it as plain text: stackoverflow.com/a/5679857/2831645 Commented Jan 18, 2019 at 15:34

2 Answers 2

2

This is quite simple to accomplish. Create the div and set its innerHTML as the template contents. Then add the div to the DOM.

You were on the right track, but just skipped the one vital step.

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>

EDIT: OP changed the use case in the question, so this updates the answer to reflect the new question :-/

Sign up to request clarification or add additional context in comments.

7 Comments

You are now adding it twice. section.innerHTML = template.replace(/\{\{title\}\}/, "Title"); and just add it once would be the way to go most likely.
@JavaScript - thanks that was an oversight. I'll correct.
@K.C. - The classList.add() method takes a comma separated list of class names to add all at once (if that's what you mean). See line 23 in the example: developer.mozilla.org/en-US/docs/Web/API/Element/…
@RandyCasburn thanks. I'm wanting to challenge this solution when there is an array of data. The class seems to only apply to the first element. I'll update my codes above with the test data. Would u take a look at it, please?
@K.C. - You cannot do that with your current template because you set an id attribute in your template. While creating multiple elements from that template you will duplicate that id value which is not allowed (ids must be unique).
|
0

If you specify a content type other than Javascript in Script tags (or another scripting language that the browser understands), it will not be interpreted by the browser, and you can just access it as plain text.

refer( How does HTML tags work inside script tag? )

you do not have the html DOM that you put in you script but you are trying to query on it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.