3

I'm trying to add an element to the DOM using JavaScript. I have a ul and I want to add a li. Its nothing difficult using appendChild but I want my li to be more complicated.

This is the output that I'm trying to achieve:

<li>
  <span class="author">Me</span>
  <span class="message">Message...</span>
  <span class="time">
    <div class="line"></div>
    15:21
  </span>
</li>
let author = "me";
let message = "Message...";
let time = "15:21";

As you can see what I'm trying to achieve isn't just a basic li with some text (innerHTML) but quite a big chunk of HTML code.

My question is how I can achieve to get this output using JavaScript. Or should I use some JavaScript library or something to make it easier?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Michal K
  • 213
  • 2
  • 3
  • 10
  • 1
    Please post your attempt. If you click edit and then `[<>]` snippet editor you can give us a [mcve] – mplungjan Mar 17 '20 at 12:48
  • 1
    What's the problem with `.appendChild()`? Build the `
  • ` with all its child elements and then just append the `
  • `
  • – Andreas Mar 17 '20 at 12:49
  • 2
    But in the end this is still invalid markup. A `
    ` is not a valid child of a [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span)
    – Andreas Mar 17 '20 at 12:50
  • why would you put a
    into a ?? a span is an inline element, while a div is a block element. this is bad code
    – Iamnino Mar 17 '20 at 12:51
  • @Andreas I'm still a junior developer and I was thinking if there was a better solution for my problem. Like JSX in React so I could write HTML inside javascript. And thanks for telling me about the ``. – Michal K Mar 17 '20 at 12:54
  • 1
    `div` is perfectly valid child in a span, provided its CSS property `display` was set to `inline`. – Teemu Mar 17 '20 at 12:54
  • The larger question is: why is OP using a `
    ` as a presentational element (inferred from its class name) instead of CSS?
    – David Thomas Mar 17 '20 at 13:01
  • did you see my answer ? (with DOMParser) – Mister Jojo Mar 17 '20 at 13:12