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 AJAX Basics (retiring) jQuery and AJAX The Office Status Project Revisited

William Bruntrager
William Bruntrager
11,473 Points

Building long strings vs. Creating elements

It is neat to see HTML built up piece by piece as a long string, and it certainly helps get a grasp of what is going on, but it also seems to me that it would make the code harder to maintain compared to using the jQuery methods that create elements.

Would it be reasonable to say we should avoid creating HTML by building long strings in this way (if we weren't still trying to learn the basics of how jQuery works)?

1 Answer

Peter Szerzo
Peter Szerzo
22,661 Points

Hey William,

Let me know if I am misunderstanding your question, but if you mean that attaching a DOM element generated by JavaScript in a long long tring such as:

$('#some-container').html('<div><ul><li>some item</li><li>other things</li><li>more, more more</li></ul></div>');

is a bad practice, it is very much the case, as it is very difficult to maintain. The most professional alternative is a templating system, such as http://handlebarsjs.com/ or http://mustache.github.io/, but this may often be an overkill. You can just proceed as you said, building from jQuery, piece by piece. It is then good practice to build up everything before you make changes in the DOM, as piece-by-piece changes are expensive. Document fragments can help: https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment.

Peter

William Bruntrager
William Bruntrager
11,473 Points

Yep, you understood the question perfectly. Thanks for telling me about templates, it looks like an interesting option.