JavaScript Append Data to Div

  1. Use innerHTML to Append Data to Div in JavaScript
  2. Use appendChild to Append Data to Div in JavaScript
  3. Use insertAdjacentHTML() to Append Data to Div in JavaScript
  4. Use jQuery’s append() to Append Data to Div

This tutorial introduces how to append data to div using JavaScript.

Use innerHTML to Append Data to Div in JavaScript

In this method, we first select the div by using one of the selectors i.e. getElementById, getElementByTag, querySelector, etc. We then append the data to the innerHTML attribute of div. This method has one disadvantage: it removes all the existing event listeners on the selected div. It will also destroy all nodes contained inside and replace them with new ones. All references to the elements will be lost.

var targetDiv = document.getElementById('ID');
targetDiv.innerHTML += 'data that you want to add';

Use appendChild to Append Data to Div in JavaScript

Like the previous method, we first select the div by using one of the selectors. But instead of innerHTML, we use appendChild because of the problems discussed in the previous method. Before appending a child, we have to create the text node.

var targetDiv = document.getElementById('ID');
var content = document.createTextNode("data that you want to add");
targetDiv.appendChild(content);

Use insertAdjacentHTML() to Append Data to Div in JavaScript

Like the second method, this method is a better alternative to the first method. insertAdjacentHTML() doesn’t reparse the element, and it also doesn’t interfere with the existing elements inside. It is much faster than innerHTML. It also helps us specify the position at which to insert the data. Like previous methods, we first select the div, and then we use insertAdjacentHTML() to add the data at the required position.

var targetDiv = document.getElementById('ID');
targetDiv.insertAdjacentHTML('afterend', 'data that you want to add');

Use jQuery’s append() to Append Data to Div

The append function takes the input of the content that needs to be added and can be called directly on a tag using jQuery syntax. This method also has all the drawbacks of the innerHTML method.

$( ".divd" ).append( "<p>Test</p>" );
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - JavaScript DOM

  • Check if Element Exists in DOM in JavaScript