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 trial

JavaScript

Why is it ul.insertBefore(li, prevLi) instead of prevLi.insertBefore(li)?

I'm wondering why insertBefore is called on the ul variable with 2 arguments passed in (li, prevLi) as opposed to being called on the prevLi variable with li being passed in as the only argument.

1 Answer

Steven Parker
Steven Parker
243,134 Points

The second argument is not optional.

The insertBefore method is always called on the node that will become the parent of the new one, and the arguments given are both the new node and the reference node that it will be inserted before (or null). Omitting the second argument would be a syntax error, and calling the method on the reference node instead of the intended parent would place it at the wrong point in the DOM.

For complete details, see the MDN Documentation page.

Thanks for answering! So I already understood the logic behind passing in the new node and reference node as the parameters to the method being called on the parent node but was wondering why it needed to be called on the parent node in the first place. What I think you're saying is that if you did not call the method on the parent node, the new node would have no context of where to go in the DOM as "before" could mean anywhere in the DOM as long as it is before the reference node. Thus, if you do call the method on the parent node, the new node knows to stay within the bounds of its parent and insert itself exactly before the reference node. Am I understanding this correctly?

Steven Parker
Steven Parker
243,134 Points

We can only guess at the original intent of the developers, but that seems a fair description of how it operates. The important thing to remember is that the method is designed to be called on the parent, and passed both the new child node and a reference node.