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?
Use the insertAdjacentText() method to append text to a div element, e.g. container. insertAdjacentText('beforeend', 'your text here') . The method inserts a new text node at the provided position, relative to the element it was called on.
To use the innerHTML property to attach code to an element (div), first pick the element (div) where you wish to append the code. Then, using the += operator on innerHTML, add the code wrapped as strings.
First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the append() method to copy the element as its child.
Try this:
var div = document.getElementById('divID'); div.innerHTML += 'Extra stuff';
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>";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With