How to append data to DOM element in javascript?|Jquery

This short tutorial shows How to append content to a div using plain JavaScript and jQuery.

let’s define a div element in HTML

<div id="employee"></div>

Here, we want to append the data, not the HTML tags data.

Use plain javascript to append data to the div element

Native JavaScript provides the following API methods to read and update DOM elements. DOM is a Tree of nodes, that represents HTML page content.

  • getElementIById - Get DOM element for a given id="value"
  • createTextNode - Create a text node
  • createElement - Create Element

First Way,

document.createElement() is used to Create a DOM Element. Call the textContent property on the newly created element. get Element using getElementById. Finally, append a new element to the element using appendChild

var employeeDiv = document.getElementById("employee");
var divElement = document.createElement("div");
divElement.textContent = "header content";
employeeDiv.appendChild(divElement);

Second Way, using createTextNode

get Element with an id selector using the getElementById method. Next, create an object using createTextNode with data. append an object to the div element using the appendChild method

var employeeDiv = document.getElementById("employee");
var content = document.createTextNode("testcontent");
employeeDiv.appendChild(content);

Similarly, you can use the innerHTML property which adds HTML and text data. This adds a security breach to the XSS attack. Moreover, It recreates div and all the references and listeners for existing div elements and does not work as expected.

var employeeDiv = document.getElementById("employee");
employeeDiv.innerHTML += "test content";

Third, using textContent to a DOM Element

textContent method appends text data only.

var employeeDiv = document.getElementById("employee");
employeeDiv.textContent += "test content" ;

Both generate the following HTML output

<div id="employee">test content</div>

Use jQuery to append content to the div

If you use jQuery in your application, We can do it in multiple ways.

use ID selector syntax to select a div and use the append() method

$("#employee").append("test content");

Another way, use the HTML() method.

$("#employee").html("test content");