Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 448
Premature Optimizer Avatar asked Dec 15 '25 01:12

Premature Optimizer


1 Answers

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.

like image 96
Lloyd Banks Avatar answered Dec 16 '25 18:12

Lloyd Banks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!