Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialbrandonlind2
7,823 Pointswhy is appendChild showing up as not a function
I'm quite confused by this because from looking at the mdn it looks like it should exist on nodes. wrapper.appendChild(div), returns error say appendChild isnt a function
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.wrapper{
display: flex;
flex-wrap: wrap;
}
.wrapper div {
width: 25px;
height: 25px;
border: 1px solid rgba(0,0,0,.2);
}
</style>
</head>
<body>
<div class="wrapper">
<div></div>
<div></div>
</div>
</body>
<script type="text/javascript">
let wrapper=document.getElementsByClassName('wrapper');
for(i=0; i< 500; i++){
let div=document.createElement('div');
wrapper.appendChild(div);
}
</script>
</html>
1 Answer
Tijo Thomas
9,737 PointsThe appendChild() method must be called on an element as referenced in the appendChild MDN page under syntax.
You used the getElementsByClassName() method to select the wrapper div. The problem with this is that method returns an HTMLCollection, an array-like object, not the element object that's needed by the appendChild() method.
You could change your for loop to this and it should work.
for(i=0; i< 500; i++){
let div=document.createElement('div');
wrapper[0].appendChild(div);
}
Since you only have one element with the class "wrapper", I would change it to an ID and replace the getElementsByClassName() method with the getElementByID() method as this method returns an element object which will work with appendChild().
Joel Kraft
Treehouse Guest TeacherJoel Kraft
Treehouse Guest TeacherHi Brandon, I just wanted to check to see if you resolved this question. Tijo gave a thorough explanation below, but if you still have questions, I'm happy to try to explain further. :)