How to append data to div using javascript?|Jquery add content to div

This short tutorial is to append content to div in 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 div

Native javascript provides DOM elements.

First, create an element to 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 do not work as expected.

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

And also, another way, use the textContent method.

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

Both generate the following HTML output

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

Use jquery append content to div

If you use jquery in your application, It can do in multiple ways.

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

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

Another way, use html() method

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