Home >Web Front-end >JS Tutorial >How to Append Text to a DIV Without Overwriting Existing Content?
Preserving Data While Appending Text to a DIV Element
When using JavaScript and AJAX to inject content into a DIV element, it's common to face the challenge of maintaining existing data while adding new content. Here's an efficient approach to achieve this:
Solution:
To append new text while preserving existing data in a DIV, leverage the innerHTML property as follows:
var div = document.getElementById('divID'); // Append the new content div.innerHTML += 'Extra stuff';
In this technique, the = operator is crucial. It modifies the innerHTML property by concatenating the existing content with the new data. This eliminates the risk of overwriting the original content and ensures seamless appending of new text.
By implementing this solution, you can effortlessly append additional data to a DIV element while maintaining its previous content, giving you the flexibility to dynamically update your web pages.
The above is the detailed content of How to Append Text to a DIV Without Overwriting Existing Content?. For more information, please follow other related articles on the PHP Chinese website!