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

Emily Carey
Emily Carey
7,954 Points

Why not use .cloneNode?

I'm just wondering as to why we don't use .cloneNode instead, accessing a hidden template (li)element within the HTML? As this was the method I chose to solve the problem, seems to take less code and is less hassle in only changing the elements you want/need to access as and when you need them. What is best practice?

Also - is there any instance where building the element via .createElement would be better than .clone, regarding similar situations (i.e. adding an li or element with 3+ children each time)?

Rory Deken
Rory Deken
45,406 Points

The only thing you should watch out for when using this is when the element or its children (if it is a deep clone which is the default) have an id attribute then you could end up with two elements with the same id which could break the page in some way either with its display or if that element is targeted by something else. Developers use create element since they can add any properties or other modifications they need and they have more control over how the element will be replicated. Both are correct and fine, just most prefer to avoid potential bugs by adding the extra lines. Does that help?

1 Answer

Brian Steele
Brian Steele
23,060 Points

Rory is right on. Additionally, an argument could be made that createElement is little more readable for someone else who has to work on your code (i.e. in a team environment). Not saying it's the strongest argument in this case, but is another thing to consider.