Home  >  Article  >  Web Front-end  >  How to Append Text to a Div Element Using JavaScript Without Losing Existing Data?

How to Append Text to a Div Element Using JavaScript Without Losing Existing Data?

DDD
DDDOriginal
2024-11-14 18:21:02480browse

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:

  1. Identify the <div> element using its id attribute:
var div = document.getElementById('divID');
  1. Use the = operator to append the new data to the existing HTML content within the div:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn