Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append data to div using JavaScript?

Tags:

javascript

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?

like image 823
Adham Avatar asked Apr 15 '11 13:04

Adham


People also ask

How do I append something to a div?

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.

How do I append to innerHTML?

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.

How append a div in another div using jQuery?

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.


2 Answers

Try this:

var div = document.getElementById('divID');  div.innerHTML += 'Extra stuff'; 
like image 50
Naftali Avatar answered Oct 15 '22 17:10

Naftali


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>";  
like image 22
Chandu Avatar answered Oct 15 '22 17:10

Chandu