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">

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

Use plain javascript

Native javascript provides DOM elements.

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

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

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

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

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

$('#employee').append('test content')

Another way, use html() method

$("#employee").html("test content");
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.