0

Scenario:

I have an HTML unordered list.

I have a button that triggers an AJAX call that returns an HTML string that is a bunch of <li>...</li> elements in plain text.

I want to add that bunch of li elements to the ul with Javascript.

What I know:

I know I can do something like:

newLi = document.createElement("li");
document.getElementById('#the_ul').appendChild(newLi);

But I don't know how to do something like:

newBunchOfLis = createThemFromHTML('<li>hello</li><li>bye</li>');
document.getElementById('#the_ul').appendChild(newBunchOfLis);

Question:

What do you suggest?

Álvaro Franz
  • 699
  • 9
  • 26
  • 1
    [Add elements to the DOM given plain text HTML using only pure JavaScript (no jQuery)](https://stackoverflow.com/questions/10309650/add-elements-to-the-dom-given-plain-text-html-using-only-pure-javascript-no-jqu) – Andreas Mar 24 '20 at 17:03
  • See the linked question's answers. Basically, `document.getElementById("the_ul").insertAdjacentHTML( "beforeend", "
  • hello
  • bye
  • " );` (note you don't use the `#` with `getElementById`, unless you have the `#` in the `id` attribute, which I don't recommend). – T.J. Crowder Mar 24 '20 at 17:03
  • @T.J.Crowder Thanks a lot for your helpful comment. I don't know how much this is a duplicate since the question phrasing also matters. The semantics of "adding a bunch of li's" is not the same as the semantics of "adding HTML". Had I known that second concept before, I would have probably found the answer with a simple Google search. – Álvaro Franz Mar 24 '20 at 17:06
  • Don't think of "duplicate" as "bad." :-) A good duplicate helps others find the answer (in the linked question). But since you went with a string in the question, it seemed reasonable to mark it. (The other way to do it, just FWIW, is a [document fragment](https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment).) – T.J. Crowder Mar 24 '20 at 17:07
  • 1
    @T.J.Crowder Thanks. That's a great point of view. Really appreciate your effort. – Álvaro Franz Mar 24 '20 at 17:09