How to append data to
element using JavaScript?


We can append data to an <div> element using JavaScript by using the .innerHTML property to add content to the element. This can be done by using the += operator to add the new content to the existing content within the <div>. We can also use the .appendChild() method to add a new child element to the <div>.

<div>

<div> is a block-level element that is used to create a division or section in an HTML document. The element is usually used to group elements together, such as paragraphs, headings, or images. The <div> element can also be used to style a section of the document, such as adding a background color or border.

Approach

To append data to a div element using JavaScript, you would first need to select the element using a selector, then use the append() or appendChild() method to append data to the selected element.

Here is an example of how you would append a paragraph element to a div element −

var div = document.querySelector('div');
var p = document.createElement('p');
p.textContent = 'This is some data that will be appended to the div element';
div.appendChild(p);

Example

Assuming you have a div with an id of “content” −

<!DOCTYPE html>
<html>
<head>
   <title>Append Data to DIV</title>
</head>
   <body>
      <div id='content'>
         <p style='color:black;'>I existed before</p>
      </div>
      <script>
         var div = document.getElementById('content');
         var p = document.createElement('p');
         p.style.color = 'black';
         p.textContent = 'I was appended to the div';
         div.appendChild(p);
      </script>
   </body>
</html>

Updated on: 16-Feb-2023

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements