Home > Article > Web Front-end > How to Append Text to a `` Element without Data Loss?
Appending Text to a <div> Element Without Data Loss
When using AJAX to modify a <div> element's content, it's important to ensure that new data doesn't overwrite existing content. Here's a solution to this problem:
var div = document.getElementById('divID'); div.innerHTML += 'Extra stuff';
This code appends new text to the existing content of the <div> element. The innerHTML property contains the entire HTML content of the element. By using the = operator, we add to the existing content instead of replacing it.
Explanation:
The getElementById method returns a reference to the <div> element with the specified ID ("divID"). The innerHTML property contains the HTML content within that element.
The = operator appends the string "Extra stuff" to the end of the innerHTML property. This effectively adds the new text to the existing content without deleting it.
Example:
Consider a <div> element with the ID "dataDiv":
<div>
If we execute the JavaScript code:
var div = document.getElementById('dataDiv'); div.innerHTML += 'New Data';
The resulting HTML content of the <div> element will be:
<div>
This approach allows you to seamlessly update the content of a <div> element with new data without losing any existing content.
The above is the detailed content of How to Append Text to a `` Element without Data Loss?. For more information, please follow other related articles on the PHP Chinese website!