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);– jimyApr 15, 2011 at 13:55
-
63@jimy thats jquery, no need to use that for such a trivial thing– NaftaliApr 15, 2011 at 13:55
-
3@Neal sure, but he's using AJAX too, so jQuery is definitely a good idea!– AlnitakApr 15, 2011 at 14:09
-
4@Alnitak, but how do you know the OP is using jQuery for anything?– NaftaliApr 15, 2011 at 14:10
-
29@Alnitak, jQuery is not the only ajax solution– NaftaliApr 15, 2011 at 14:24
12 Answers
Try this:
var div = document.getElementById('divID');
div.innerHTML += 'Extra stuff';
-
58Danger, Will Robinson! This adds HTML, not text. If your Extra Stuff is provided by the user, you've just introduced a security vulnerabilty. Better to use @Chandu's answer below. Feb 13, 2016 at 22:50
-
10Yes, it's an XSS vulnerability. You're far better off creating a text node with the content instead, as describe in the answer below. Apr 12, 2016 at 19:50
-
2This also woudn’t work in case
div
contains elements with event listeners or inputs with user-entered text. I recommend the answer by Chandu. Apr 19, 2016 at 16:09 -
13This is not recommended, see Is it possible to append to innerHTML without destroying descendants' event listeners?– BergiOct 4, 2016 at 19:21
-
4Yes, I definitely do not recommend this as this will destroy state of any checkboxes, event listeners.– KurkulaNov 20, 2017 at 19:15
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>";
-
I use this method with my "contenteditable" element with angularjs binding, and everything work correctly!– wrongiteOct 18, 2016 at 16:04
-
1Should be the accepted answer indeed. Not only a beautiful way, but innerHTML will rebuild the DOM, and that is just not a good solution. Use appendChild(). Jan 7, 2017 at 14:53
-
6This is better, but
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.– JakeMar 13, 2017 at 5:58 -
what if we want to change the text of same appended text node in the next event ? Mar 1, 2018 at 8:06
-
2@Jake If HTML needs to be inserted instead of plain text, then don’t use
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”. Jan 5, 2022 at 22:02
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);
-
2yes but this will cause there to be an extra div inside the parent div which is not needed and might mess up some css styles– NaftaliApr 15, 2011 at 14:11
-
@Neal this is just a example way to use appendChild. the point is not here.– BiAiBApr 15, 2011 at 14:16
-
-
4@Neal no it's not. It's neither correct or incorrect. It just depends on what the OP needs to append: text, html code or something else.– BiAiBApr 15, 2011 at 14:23
-
1@Neal this is a perfectly good way of appending the data, and is more versatile than
document.createTextNode()
.– AlnitakApr 15, 2011 at 14:27
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>
-
-
1
-
6
-
1
-
If you are using jQuery you can use $('#mydiv').append('html content')
and it will keep the existing content.
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.
Even this will work:
var div = document.getElementById('divID');
div.innerHTML += 'Text to append';
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
.insertAdjacentHTML
when deliberately inserting HTML - using it unnecessarily is less semantically appropriate and can increase the risk of XSS) - Flexible; the first argument to
.insertAdjacentText
may bebeforebegin
,beforeend
,afterbegin
,afterend
, depending on where you'd like the text to be inserted
you can use jQuery. which make it very simple.
just download the jQuery file add jQuery into your HTML
or you can user online link:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
and try this:
$("#divID").append(data);
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");
java script
document.getElementById("divID").html("this text will be added to div");
jquery
$("#divID").html("this text will be added to div");
Use .html()
without any arguments to see that you have entered.
You can use the browser console to quickly test these functions before using them in your code.
-
-
innerHtml and html() worked differently on my project. innerHtml did nothing in one scenario. So added it, in case its the same for anyone else. Feb 22, 2017 at 0:59
-
Neither an
innerHtml
nor anhtml
property exists anywhere on the prototype chain ofHTMLElement
s. The jQuery alternative has all the drawbacks of the (unfortunately) accepted answer, and it requires an unnecessary dependency. Aug 28, 2020 at 3:42
Why not just use setAttribute ?
thisDiv.setAttribute('attrName','data you wish to append');
Then you can get this data by :
thisDiv.attrName;
-
1