Premature Optimizer
Premature Optimizer

Reputation: 237

Adding HTML to the end of a container: What is the proper way to do it using JavaScript?

I'm a bit of a web dev n00b, so I do things like this:

document.getElementById("some_element").innerHTML += "<p>Here's some more that will be added to the end of the HTML that composes some_element</p>";

However, I'm guessing there's a purer way of accomplishing the task of modifying inner HTML. What is the standard way of doing this? I assume this sort of procedure is what happens when I post something on an internet forum. So, it's kind of an important thing to know.

Upvotes: 3

Views: 1853

Answers (2)

Lloyd Banks
Lloyd Banks

Reputation: 36659

I recommend using appendChild over innerHTML

myDiv = document.getElementById("myid");
myNewNode = document.createElement("div")
myContent = document.createTextNode("text of new div");
myNewNode.appendChild(myContent);
myDiv.appendChild(myNewNode);

innerHTML will remove listeners that are on your existing nodes within the element. appendChild preserves them.

Upvotes: 5

cookie monster
cookie monster

Reputation: 10972

If you want to create and append nodes via HTML markup, do so by using .insertAdjacentHTML().

elem.insertAdjacentHTML("beforeend", "<p>Here's some more that will be added to the end of the HTML that composes some_element</p>");

Otherwise, use DOM creation/manipulation methods.

elem.appendChild(document.createElement("p"))
    .appendChild(document.createTextNode("Here's some more that will be added to the end of the HTML that composes some_element"));

Upvotes: 1

Related Questions