Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) Making Changes to the DOM Appending Nodes

Another way of inserting the Li as a child element of the UL

Hi everyone,

In another JavaScript Course, Guil explains another method of inserting html.

I understand using the .appendChild() method but is there any reason why you couldn't do the same with .insertAdjacentHTML("beforeend", 'li') ?



3 Answers

Steven Parker
Steven Parker
229,982 Points

The "insertAdjacentHTML" method requires complete HTML for the second argument, so the correct syntax a single substitute statement would be:

ul.insertAdjacentHTML("beforeend", li.outerHTML);

But this leaves the newly created element unattached. A better approach wold be to skip the create statement entirely and do this:

ul.insertAdjacentHTML("beforeend", `<li>${addItemInput.value}</li>`);

This is also a newer method so it may not have as much browser support. But if you don't mind using "bleeding edge" tech, an even newer substitute for "appendChild" is simply "append", which does attach the element in the same way.

Daniel L.
Daniel L.
10,837 Points

I also did it another way. I gave my <ul> an ide of #unordered and assigned it to a variable called list

const list = document.querySelector("#unordered");

I then wrote the function like this:

addItemButton.addEventListener("click", () => {
  let li = document.createElement("li");
  let item = li.textContent = addItemInput.value;
  list.innerHTML += `<li>${item}</li>`;
  addItemInput.value = "";


Just a suggestion :)

Steven Parker
Steven Parker
229,982 Points

Since the textContent gets wiped out when you assign the innerHTML (which is a difference from the other methods shown), you can simplify that assignment of "item":

  let item = addItemInput.value;

This also avoids having two assignments in the same statement, which can be a bit confusing.

Daniel L.
Daniel L.
10,837 Points

Oh cool thanks Steven!