Reputation: 21
I am building a simple script to understand how mvc works. I'm new to this and like to see if anyone out there can help me with this. I can't get my render function to display the content from the model. I get an error in my console:
"app.js:33 Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'."
Any help with this would be appreciated.
var model = {
farm: {
cow: "Moo!",
pig: "Oink!",
duck: "Quack!"
}
};
var controller = {
init: function() {
farmView.init();
},
getBarn: function() {
return model.farm;
}
};
var farmView = {
init: function() {
this.barn = document.getElementById('farm');
this.render();
},
render: function() {
var animals = controller.getBarn();
var examplediv = document.getElementById('cow');
this.barn.innerHTML = '';
var htmlStr = '';
htmlStr += '<span>' + model.farm.cow + '</span>' + '<span>' + model.farm.pig + '</span>';
this.barn.appendChild(htmlStr);
examplediv.appendChild(htmlStr);
}
};
controller.init();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Farmcow</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="farm">
<div id="cow"></div>
</div>
<script src="app.js"></script>
</body>
</html>
Upvotes: 0
Views: 645
Reputation: 51816
As the error points out, appendChild()
expects a Node
, not a string. Use insertAdjacentHTML()
with the argument beforeend
:
var model = {
farm: {
cow: "Moo!",
pig: "Oink!",
duck: "Quack!"
}
};
var controller = {
init: function() {
farmView.init();
},
getBarn: function() {
return model.farm;
}
};
var farmView = {
init: function() {
this.barn = document.getElementById('farm');
this.render();
},
render: function() {
var animals = controller.getBarn();
this.barn.innerHTML = '';
var htmlStr = '';
htmlStr += '<span>' + model.farm.cow + '</span> <span>' + model.farm.pig + '</span>';
this.barn.insertAdjacentHTML('beforeend', htmlStr);
}
};
controller.init();
<div id="farm"></div>
Upvotes: 1
Reputation: 48230
The error message seems to say it clearly, what you pass as an argument to the appendChild
is not of a Node type, it's a string.
You possibly meant to call document.createElement
first to have a new element, then set its innerHTML
and only then append it. This will work, as the newly created element will have a type accepted by the appendChild
.
Upvotes: 0