463

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?

Sebastian Simon
  • 16,564
  • 7
  • 51
  • 69
Adham
  • 61,516
  • 96
  • 221
  • 343

11 Answers11

668

Try this:

var div = document.getElementById('divID');

div.innerHTML += 'Extra stuff';
Seth McClaine
  • 7,625
  • 6
  • 37
  • 56
Naftali
  • 142,114
  • 39
  • 237
  • 299
  • 51
    Danger, 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. – David Given Feb 13 '16 at 22:50
  • Refering to the reply of @DavidGiven is it really a security problem? if it is what could be safe? – Muneeb Mirza Apr 11 '16 at 08:07
  • 10
    Yes, it's an [XSS vulnerability](https://en.wikipedia.org/wiki/Cross-site_scripting). You're far better off creating a text node with the content instead, as describe in the answer below. – David Given Apr 12 '16 at 19:50
  • 2
    This also woudn’t work in case `div` contains elements with event listeners or inputs with user-entered text. I recommend the [answer by Chandu](http://stackoverflow.com/a/5677825/4642212). – Sebastian Simon Apr 19 '16 at 16:09
  • 11
    This is not recommended, see [Is it possible to append to innerHTML without destroying descendants' event listeners?](http://stackoverflow.com/q/595808/1048572) – Bergi Oct 04 '16 at 19:21
  • I tried this solution with document.getElementsByClassName instead of getElementByID. With ID it works, but with ClassName it doesn't. Why is this? – D.Bronder Sep 07 '17 at 16:29
  • Because classname returns you a list whereas ID returns only one – Naftali Sep 07 '17 at 16:30
  • what if the element has a class with name on it. Instead of getElementById can we use classname? – Kurkula Nov 14 '17 at 19:15
  • 4
    Yes, I definitely do not recommend this as this will destroy state of any checkboxes, event listeners. – Kurkula Nov 20 '17 at 19:15
  • 1
    As others have said, do not do this ! Append a child TextNode, see @Chandu’s answer. – Sxilderik Jun 15 '18 at 10:49
  • Doing this will destroy event listeners as stated in [this answer](https://stackoverflow.com/a/5677950/4284627). – Donald Duck Jan 15 '19 at 14:50
  • How do you add a space to the div? – Andrei Mar 01 '20 at 21:15
  • This should be mentioned from the comment below: https://stackoverflow.com/a/34551817/6058482 – James Bellaby Jan 22 '21 at 12:30
388

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>"; 
Chandu
  • 78,650
  • 19
  • 129
  • 131
  • I use this method with my "contenteditable" element with angularjs binding, and everything work correctly! – wrongite Oct 18 '16 at 16:04
  • 1
    Should 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 Sverre Jan 07 '17 at 14:53
  • 6
    This 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. – Jake Mar 13 '17 at 05:58
  • what if we want to change the text of same appended text node in the next event ? – Rahul Mishra Mar 01 '18 at 08:06
  • This is much easier with the [more recent](//developer.mozilla.org/docs/Web/API/Element/append#browser_compatibility) [`theDiv.append("The additional content.")`](//developer.mozilla.org/docs/Web/API/Element/append). – Sebastian Simon Jan 05 '22 at 22:00
  • 1
    @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`](//developer.mozilla.org/docs/Web/API/Element/insertAdjacentHTML), [`insertAdjacentElement`](//developer.mozilla.org/docs/Web/API/Element/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”. – Sebastian Simon Jan 05 '22 at 22:02
139

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);
Donald Duck
  • 7,638
  • 19
  • 69
  • 90
BiAiB
  • 11,493
  • 7
  • 40
  • 59
  • 2
    yes 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 – Naftali Apr 15 '11 at 14:11
  • @Neal this is just a example way to use appendChild. the point is not here. – BiAiB Apr 15 '11 at 14:16
  • The correct way to do the `appendChild` was done by @Cybernate – Naftali Apr 15 '11 at 14:17
  • 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. – BiAiB Apr 15 '11 at 14:23
  • 1
    @Neal this is a perfectly good way of appending the data, and is more versatile than `document.createTextNode()`. – Alnitak Apr 15 '11 at 14:27
69

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>
Aaron
  • 1,330
  • 1
  • 15
  • 30
Milan Rakos
  • 1,615
  • 17
  • 23
17

If you are using jQuery you can use $('#mydiv').append('html content') and it will keep the existing content.

http://api.jquery.com/append/

cweston
  • 10,827
  • 18
  • 79
  • 106
11

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.

Community
  • 1
  • 1
LGT
  • 4,889
  • 1
  • 20
  • 20
8

Even this will work:

var div = document.getElementById('divID');

div.innerHTML += 'Text to append';
slavoo
  • 5,437
  • 64
  • 35
  • 39
Macfer Ann
  • 153
  • 1
  • 9
2

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);
Vishnu Mishra
  • 3,326
  • 2
  • 23
  • 35
1

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");
Umbert
  • 1,123
  • 2
  • 9
  • 22
-1

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.

Deepu Sahni
  • 379
  • 2
  • 9
  • This is a copy of the accepted answer an one other. Why? – Stephen Rauch Feb 10 '17 at 04:20
  • 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. – Deepu Sahni Feb 22 '17 at 00:59
  • Neither an `innerHtml` nor an `html` property exists anywhere on the prototype chain of [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement)s. The jQuery alternative has all the drawbacks of the (unfortunately) [accepted answer](https://stackoverflow.com/a/5677816/4642212), _and_ it requires an unnecessary dependency. – Sebastian Simon Aug 28 '20 at 03:42
-3

Why not just use setAttribute ?

thisDiv.setAttribute('attrName','data you wish to append');

Then you can get this data by :

thisDiv.attrName;
thatOneGuy
  • 9,252
  • 6
  • 42
  • 84