CosmicEon CosmicEon - 2 months ago 7
Javascript Question

How to read object properly in JavaScript

I am new to programming and recently began learning Javascript, I have a problem that appeared in few exercises that I made. I searched the site for more information but have not found a solution for my problem. I apologize in advance for my bad english and if this is not the right place or the right way to ask this question because this is my first post in Stackoverflow.

Currently practicing HTML templates. Assuming that the code is correct, I'm not sure where I'm wrong. Loading code into the browser and Handlebars gives me an error: "Error: You must pass a string or Handlebars AST to Handlebars.compile. You passed undefined". I tried to debug and saw that when I tried to take a value from

object it gives back undefined. In previous exercise had a similar problem in which I tried to read JSON object and did not manage to parse it and returned again undefined. Can you help me, I am stuck on this problem for some time.

var data = {
animals: [{
name: 'Lion',
url: ''
}, {
name: 'Turtle',
url: ''
}, {
name: 'Dog'
}, {
name: 'Cat',
url: ''
}, {
name: 'Dog Again'

window.onload = function() {
var htmlTemplate = document.getElementsByClassName('container-template').innerHTML;
var template = Handlebars.compile(htmlTemplate);

for (let x of data.animals) {
if (x.hasOwnProperty('url')) { //x.url
x.hasUrl = true;
} else {
x.hasUrl = false;

document.getElementsByClassName('container').innerHTML = template(data);

<!DOCTYPE html>


<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Animals & Batman</title>


<div class="container">

<script class="container-template" type="text/x-handlebars-template">
{{#each animals}}
{{#if hasUrl}}
<a href="{{url}}">See a {{name}}</a>
<a href="">No link for {{name}}, here is Batman!</a>

<script src="../handlebars-v4.0.5.js" charset="utf-8"></script>
<script src="../jquery-3.1.0.js" charset="utf-8"></script>
<script src="./main.js" charset="utf-8"></script>



document.getElementsByClassName returns an array of elements, not a single one - since multiple elements on a page can have the same class.

What you probably want is to use the id instead of class:

<script id="container-template" type="text/x-handlebars-template">

var htmlTemplate = document.getElementById('container-template').innerHTML;