Pretty simple question that I couldn’t find an answer to, maybe because it’s a non-issue, but I’m wondering if there is a difference between creating an HTML object using Javascript or using a string to build an element. Like, is it a better practice to declare any HTML elements in JS as JS objects or as strings and let the browser/library/etc parse them? For example:
jQuery('<div />', {'class': 'example'});
vs
jQuery('<div class="example></div>');
(Just using jQuery as an example, but same question applies for vanilla JS as well.)
It seems like a non-issue to me but I’m no JS expert, and I want to make sure I’m doing it right. Thanks in advance!
They’re both “correct”. And both are useful at different times for different purposes.
For instance, in terms of page-speed, these days it’s faster to just do something like:
The browser will spit it out in an instant.
As a matter of safety, when dealing with user-input, it’s safer to build elements, attach them to a
documentFragmentand then append them to the DOM (or replace a DOM node with your new version, or whatever).Consider:
Versus:
One does bad things and one doesn’t.
Of course, you don’t have to create
textNodes, you could useinnerTextortextContentor whatever (the browser will create the text node on its own).But it’s always important to consider what you’re sharing and how.
If it’s coming from anywhere other than a place you trust (which should be approximately nowhere, unless you’re serving static pages, in which case, why are you building html?), then you should keep injection in mind — only the things you WANT to be injected should be.