-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.

Bryantee
  • 474
  • 1
  • 6
  • 12
  • 2
    um... as one string? There is no "right" answer – epascarello Sep 20 '17 at 17:22
  • 1
    "Best practice" questions are generally considered off-topic. You can also use string concatenation. –  Sep 20 '17 at 17:22
  • 2
    Maybe you want: https://stackoverflow.com/questions/508269/how-do-i-break-a-string-across-more-than-one-line-of-code-in-javascript – epascarello Sep 20 '17 at 17:24
  • 1
    Performance you can easily benchmark; readability and maintainability are mostly subjective - choose yourself. – Bergi Sep 20 '17 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. – Bryantee Sep 20 '17 at 20:47

1 Answers1

-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

tnovau
  • 23
  • 5
  • This seems reasonable, but my HTML string is going to be quite a few lines longer and I need something a bit more terse. – Bryantee Sep 20 '17 at 20:51