JavaScript JavaScript and the DOM Making Changes to the DOM Appending Nodes

Anthony Sabberton
Anthony Sabberton
4,864 Points

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') ?

Cheers,

Tony

3 Answers

Steven Parker
Steven Parker
203,717 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.
8,436 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
203,717 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.
8,436 Points

Oh cool thanks Steven!