-1

I'm currently working in a complex project without a transpiler so unfortunately I can't use any es6 syntax. What is the best practice (performance, readability, maintainability, etc.) for building HTML strings in a JS file.

Currently I'm doing it like this:

var someHTML = [
  '<div id="item-1">foo</div>',
  '<div id="item-2">bar</div>'
].join('\n');

[EDIT] I realize similar questions have been asked, but to clarify, I'm going specifically for HTML (ability to compose and read like regular HTML is important) and I would rather not rely on jQuery. When I say best practice, I realize there's more than one "right" answer, rather I would like to explore opinions and tradeoffs between patterns.

5
  • 2
    um... as one string? There is no "right" answer Commented Sep 20, 2017 at 17:22
  • 1
    "Best practice" questions are generally considered off-topic. You can also use string concatenation. Commented Sep 20, 2017 at 17:22
  • 2
    Maybe you want: stackoverflow.com/questions/508269/… Commented Sep 20, 2017 at 17:24
  • 1
    Performance you can easily benchmark; readability and maintainability are mostly subjective - choose yourself. Commented Sep 20, 2017 at 17:26
  • @espescarello Please see my latest edit, I don't think this is really a duplicate based on those proposed answers. I'm not talking about how to concatenate, but specifically around composing HTML. I also don't want to rely on jQuery if possible. Commented Sep 20, 2017 at 20:47

1 Answer 1

-2

You can use:

var fooDiv = document.createElement("div");
var barDiv = document.createElement("div");

fooDiv.id = "item-1";
barDiv.id = "item-2";

fooDiv.innerHTML = "foo";
barDiv.innerHTML = "bar";

document.body.appendChild(fooDiv);
document.body.appendChild(barDiv);

I think it works for you

Sign up to request clarification or add additional context in comments.

1 Comment

This seems reasonable, but my HTML string is going to be quite a few lines longer and I need something a bit more terse.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.