Add InnerHTML instead of replacing

I use this code to update a div using an AJAX request

 var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("some_id").innerHTML += xmlhttp.responseText; } } xmlhttp.open("GET", "http://example.com/"); xmlhttp.setRequestHeader('Content-Type', 'utf8'); xmlhttp.send(); 

Everything works fine, the problem is that when there is a lot of content in the div with id some_id , I see that the content disappears and then appears after updating the AJAX request.

I think this is because

 document.getElementById("some_id").innerHTML += xmlhttp.responseText; 

Deletes and replaces the innerHTML div with the previous innerHTML plus new content, resulting in the behavior of previous content β†’ blank β†’ updated content .

Is there a way to add new content to a div instead of replacing all of it with new content?

+7
javascript html
source share
3 answers

Assuming htmlhttp.responseText is node:

 document.getElementById("some_id").appendChild(xmlhttp.responseText); 

If you only have an HTML string (which seems likely), then:

 var newElement = document.createElement('div'); newElement.innerHTML = xmlhttp.responseText; document.getElementById("some_id").appendChild(newElement); 

On the other hand, if you have to add new elements from a string:

 // getting a reference to the relevant element we're adding to: var container = document.getElementById("some_id"), // creating a new element to contain the 'xmlhttp.responseText' newElement = document.createElement('div'); // setting the innerHTML of the 'newElement' to whatever 'xmlhttp.responseText' is: newElement.innerHTML = xmlhttp.responseText; /* (repeatedly) removing the firstChild, and appending it to the 'container', of the 'newElement' until it empty: */ while (newElement.firstChild) { container.appendChild(newElement.firstChild); } // removing the now empty 'newElement': newElement.parentNode.removeChild(newElement); 

Literature:

+12
source share

You can use Element.insertAdjacentHTML() .

insertAdjacentHTML () parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at the specified position . It does not repeat the element on which it is used, and thus, it does not damage existing elements within the element. This and avoiding the extra step of serialization makes it much faster than directly manipulating innerHTML.

I think you would do

 const div = document.getElementById("some_id"); div.insertAdjacentHTML('beforeend', xmlhttp.responseText);; 
+5
source share
 old_html = document.getElementById("some_id").innerHTML; document.getElementById("some_id").innerHTML = old_html+xmlhttp.responseText; 
+3
source share

All Articles