Reputation: 21
I am getting this error in my code. I tried adding ".nodeType" when grabbing the node, to see if it was a node and when i add an "alert" in JS i get 1. So this means it is definitely a node right?
This code is for a matching game, I separate the document into two (nodes) and generate smiley faces randomly on one side, the left hand side. The end game is to clone the exact same faces onto the second node, the RHS of the page, then remove one. The user then has to click on the extra smiley on the LHS of the page.
Anyway, I am not there yet and I am simply trying to generate smileys on one side of the page, by appending a child node to the <div>
which is the LHS of the page but it will not work and I don't see why not. Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<style>
img {position:absolute;}
/*here i tried to use 500px in the style rules for the div but the division was noticeably off centre, therefore, i used 50% instead*/
div {position:absolute; width:50%; height:50%}
#rightSide {left:50%; border-left: 1px solid black}
</style>
</head>
<body onload="generateFaces()">
<h1 id="TitleOfGame">Matching Game!</h1>
<p id="Intructions">To play the game, find the extra smiley on the left hand side and click on it :)</p>
<div id="leftSide">
<!--this div node will display all of the faces on the left side of the screen
faces are dynamically added using javascript-->
</div>
<div id="rightSide">
<!--this div node will display all of the faces on the right side of the screen
cloneNode(true) is used to copy the faces to the right side, and the last child of this branch is deleted, such that there are more faces on the left side.
-->
</div>
</body>
<script>
var numberOfFaces=5;
var theLeftSide = document.getElementById("leftSide");
var i=0;
function generateFaces(){
while (i<numberOfFaces){
var random_top=((Math.random()*400));
var random_left=((Math.random()*400));
var random_top=Math.floor(random_top);
var random_left=Math.floor(random_left);
var img=document.createElement('img');
img.src="smile.png";
img.style.left=random_left;
img.style.top=random_top;
theLeftSide.appendChild("img");
i+=1;
}
}
</script>
</html>
Trying to run this in chrome gives the above error for line 40 ie.
theLeftSide.appendChild("img");
And it does this no matter where i put the <script>
in the program :/
I have been trying for ages, can anyone tell me?
Upvotes: 1
Views: 2621
Reputation: 1074038
Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. BUT when tested using nodetype it returns 1
No, the type of what you're passing in is string.
theLeftSide.appendChild("img");
// This is parameter 1 ^^^^^
appendChild
expects a node, not a string. Looking at your code, all you have to do is remove the quotes:
theLeftSide.appendChild(img);
...as you've already created the element and assigned it to a variable called img
.
Upvotes: 1