Search code examples
javascriptappendchild

TypeError appendChild Javascript


I'm trying to insert a few links before the end tag of my NAV element, so after the rest of the links within that element. However, I keep running in to the error message "Uncaught TypeError: Cannot read property 'appendChild' of undefined" and I cannot figure out where/what the TypeError is. What am I missing? /: PS! I understand that "let" (or "const") is a replacement of var, in some instances, but I don't know if it's something to use here or not.

NOTE: I ended up here: enter link description here and then JavaScript closure inside loops – simple practical example but without any avail. There I tried 'stemon''s examples but I couldn't figure out where I should add my appendChild without still getting the same error. i.e: None of those threads gives me an understanding of what I am actually missing here.. They may give me an answer, but not one I can grasp obviously.

var node = document.getElementsByTagName("NAV");
ele = document.createElement("a");
var stepup = 0;

for (stepup = 0; stepup < 8; stepup++) {
	ele.innerHTML = 'test';
	node.parentNode.appendChild(ele, node.nextSibling);
	console.log(stepup);
}
<nav style="overflow:scroll;">
			<h3>Menu</h3>
			<a href="#">Link 1</a><br>
			<a href="#">Link 2</a><br>
			<a href="#">Link 3</a><br>
			<a href="#">Link 4</a><br>
			<a href="#">Link 5</a><br>
			<a href="#">Link 6</a>
</nav>

[Here's a fiddle also]


Solution

  • document.getElementsByTagName("nav")returns an Array of all matching elements, then you have to pick the first one.

    You are instantiating only one element because your line ele = document.createElement("a");is outside the loop.

    You don't need parentNode at all.

    Here is the forked Fiddle

    The let keyword allows to create a variable that is scoped to the wrapping block. Otherwise the variables are scoped to the parent function, but it has nothing to do with the problems you were experiencing.

    Closures are something you may learn later, it is useful when doing asynchronous operations into loops, and many other things, but does not need to be used in your case.