Home > Article > Web Front-end > How to Append Text to a Div Element Using JavaScript Without Losing Existing Data?
Appending Text to a div Element Without Data Loss
When utilizing AJAX to append data to a <div> element that is populated through JavaScript, preserving existing data can be crucial. This article explores a method to achieve this without data loss.
Solution:
To append new data to a <div> element without losing the existing content, follow these steps:
var div = document.getElementById('divID');
div.innerHTML += 'Extra stuff';
Example:
Consider the following HTML structure:
<div>
If you want to append "New data" to this <div> without removing the existing content, you can use the following JavaScript code:
var div = document.getElementById('myDiv'); div.innerHTML += 'New data';
After executing this JavaScript code, the <div> will contain the following content:
<div>
By utilizing the = operator, you can seamlessly append new data to a <div> element while preserving its existing content.
The above is the detailed content of How to Append Text to a Div Element Using JavaScript Without Losing Existing Data?. For more information, please follow other related articles on the PHP Chinese website!