I’m using AJAX to append data to a <div> element, where I fill the <div> from JavaScript. How can I append new data to the <div> without losing the previous data found in it?
-
10$(div).append(data);jimy– jimy2011-04-15 13:55:13 +00:00Commented Apr 15, 2011 at 13:55
-
65@jimy thats jquery, no need to use that for such a trivial thingNaftali– Naftali2011-04-15 13:55:33 +00:00Commented Apr 15, 2011 at 13:55
-
3@Neal sure, but he's using AJAX too, so jQuery is definitely a good idea!Alnitak– Alnitak2011-04-15 14:09:15 +00:00Commented Apr 15, 2011 at 14:09
-
4@Alnitak, but how do you know the OP is using jQuery for anything?Naftali– Naftali2011-04-15 14:10:15 +00:00Commented Apr 15, 2011 at 14:10
-
29@Alnitak, jQuery is not the only ajax solutionNaftali– Naftali2011-04-15 14:24:46 +00:00Commented Apr 15, 2011 at 14:24
11 Answers
Try this:
var div = document.getElementById('divID');
div.innerHTML += 'Extra stuff';
15 Comments
div contains elements with event listeners or inputs with user-entered text. I recommend the answer by Chandu.Using appendChild:
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
var content = document.createTextNode("<YOUR_CONTENT>");
theDiv.appendChild(content);
Using innerHTML:
This approach will remove all the listeners to the existing elements as mentioned by @BiAiB. So use caution if you are planning to use this version.
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
theDiv.innerHTML += "<YOUR_CONTENT>";
8 Comments
createTextNode won't work if you are loading HTML. If you wanted to add list items, for example, this wouldn't work. That is pretty limiting.createTextNode. There are several other methods for DOM manipulation related to this, e.g. insertAdjacentHTML, insertAdjacentElement, etc. Can’t call it “limiting” if you’re using the wrong tools. The question, though, could be clearer as to what is meant by “data”.Beware of innerHTML, you sort of lose something when you use it:
theDiv.innerHTML += 'content';
Is equivalent to:
theDiv.innerHTML = theDiv.innerHTML + 'content';
Which will destroy all nodes inside your div and recreate new ones. All references and listeners to elements inside it will be lost.
If you need to keep them (when you have attached a click handler, for example), you have to append the new contents with the DOM functions(appendChild,insertAfter,insertBefore):
var newNode = document.createElement('div');
newNode.innerHTML = data;
theDiv.appendChild(newNode);
5 Comments
appendChild was done by @Cybernatedocument.createTextNode().If you want to do it fast and don't want to lose references and listeners use: .insertAdjacentHTML();
"It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element. This, and avoiding the extra step of serialization make it much faster than direct innerHTML manipulation."
Supported on all mainline browsers (IE6+, FF8+,All Others and Mobile): http://caniuse.com/#feat=insertadjacenthtml
Example from https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>
5 Comments
insertAdjacentElement() and insertAdjacentText().If you are using jQuery you can use $('#mydiv').append('html content') and it will keep the existing content.
Comments
IE9+ (Vista+) solution, without creating new text nodes:
var div = document.getElementById("divID");
div.textContent += data + " ";
However, this didn't quite do the trick for me since I needed a new line after each message, so my DIV turned into a styled UL with this code:
var li = document.createElement("li");
var text = document.createTextNode(data);
li.appendChild(text);
ul.appendChild(li);
From https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent :
Differences from innerHTML
innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.
Comments
An option that I think is better than any of the ones mentioned so far is Element.insertAdjacentText().
// Example listener on a child element
// Included in this snippet to show that the listener does not get corrupted
document.querySelector('button').addEventListener('click', () => {
console.log('click');
});
// to actually insert the text:
document.querySelector('div').insertAdjacentText('beforeend', 'more text');
<div>
<button>click</button>
</div>
Advantages to this approach include:
- Does not modify the existing nodes in the DOM; does not corrupt event listeners
- Inserts text, not HTML (Best to only use
.insertAdjacentHTMLwhen deliberately inserting HTML - using it unnecessarily is less semantically appropriate and can increase the risk of XSS) - Flexible; the first argument to
.insertAdjacentTextmay bebeforebegin,beforeend,afterbegin,afterend, depending on where you'd like the text to be inserted
1 Comment
append()/prepend()? What disadvantages of these methods are known to you? Thanks.Even this will work:
var div = document.getElementById('divID');
div.innerHTML += 'Text to append';
1 Comment
The following method is less general than others however it's great when you are sure that your last child node of the div is already a text node. In this way you won't create a new text node using appendData MDN Reference AppendData
let mydiv = document.getElementById("divId");
let lastChild = mydiv.lastChild;
if(lastChild && lastChild.nodeType === Node.TEXT_NODE ) //test if there is at least a node and the last is a text node
lastChild.appendData("YOUR TEXT CONTENT");
Comments
1. My choice
Unicorn code style checker recommends using Vanilla JS methods append() and prepend() instead of methods insertAdjacentElement() and insertAdjacentText().
2. Demonstration
Live demonstration on LiveCodes:
kiraGoddessDiv = document.createElement("div")
kiraGoddessDiv.textContent = "is"
kiraGoddessDiv.prepend("Kira ")
kiraGoddessDiv.append(" Goddess!")
console.log(kiraGoddessDiv.textContent)
Result in console:
Kira is Goddess!
3. Advantages
3.1. “InnerHTML” disadvantages
In the article “Why InnerHTML Is a Bad Idea and How to Avoid It?” software engineer Dhairya Shah lists the inherent disadvantages of innerHTML:
- Security risk
- Slow process
- Can break the document
- Appending is not supported
- Content is replaced everywhere
3.2. Advantages over “insertAdjacentElement()” and “insertAdjacentText()”
Description of the Unicorn prefer-modern-dom-apis rule, why prefer one of .after(), .append(), .before() or .prepend() over insertAdjacentElement() and insertAdjacentText():
There are some advantages of using the newer DOM APIs, like:
- Traversing to the parent node is not necessary.
- Appending multiple nodes at once.
- Both
DOMStringand DOM node objects can be manipulated.
4. Browser compatibility
Chrome, Firefox, Opera and Safari supports append() and prepend() since 2016, Edge — since 2018.
5. Security
5.1. “append()” and “prepend()” safety
I haven’t found any information that using append() and prepend() entails any security problems.
5.2. “InnerHTML” and “insertAdjacentText()” safety
Dhairya Shah in the article mentioned above wrote:
The website can become very vulnerable if innerHTML is used constantly. For instance, using it for input fields can cause DOM manipulation, and attackers can use cross-site scripting (XSS) to insert harmful scripts and steal the private and sensitive data stored in session cookies.
The idea behind an XSS attack with innerHTML is that malicious code is injected into your site and then executed. This is possible because innerHTML renders complete markup rather than just text.
Stack Overflow user @CertainPerformance with a reputation of more than 362 thousand points wrote that “In terms of security, insertAdjacentHTML is not really better than innerHTML”
5.3. no-unsanitized
Mozilla’s developers have written an ESLint plugin no-unsanitized that warns users about unsafe use of innerHTML, insertAdjacentHTML() and alike. Examples of not allowed practices from the plugin documentation:
foo.innerHTML = input.value;
bar.innerHTML = "<a href='"+url+"'>About</a>";
Examples of allowed practices:
foo.innerHTML = 5;
bar.innerHTML = "<a href='/about.html'>About</a>";
bar.innerHTML = escapeHTML`<a href='${url}'>About</a>`;
6. Relevance of the answer
This answer is relevant as of February 2024. In the future, data of my answer may be obsolete.

