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?

5
  • 1
    Add elements to the DOM given plain text HTML using only pure JavaScript (no jQuery) Commented Mar 24, 2020 at 17:03
  • See the linked question's answers. Basically, document.getElementById("the_ul").insertAdjacentHTML( "beforeend", "<li>hello</li><li>bye</li>" ); (note you don't use the # with getElementById, unless you have the # in the id attribute, which I don't recommend). Commented Mar 24, 2020 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. Commented Mar 24, 2020 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.) Commented Mar 24, 2020 at 17:07
  • 1
    @T.J.Crowder Thanks. That's a great point of view. Really appreciate your effort. Commented Mar 24, 2020 at 17:09

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.