×

How to append HTML code to a div using JavaScript?

In HTML, we have a div tag which is used to create a box where we can put a lot of other tags. So it works like a container. So, to append any html code to the div tag, simply use the code and write between these tags. If we want to add any html code dynamically to a particular div tag, then we have to target or selectively choose that particular tag using either className or id name.

As we know, we can afford two or more divs with the same className, so using className will append the code to each div with that class name. So generally, we prefer to use an id name instead of a class name.

We can use two methods or attributes to target and append our HTML code:

  1. Using innerHTML attribute
  2. Using insertAdjacentElement() method to that element.

1.innerHTML attribute

Syntax:

targeted_element.innerHTML=targeted_element.innerHTML+new_HTMLcode

We can use shorthand properties of adding like:

targeted_element.innerHTM+=new_HTMLcode

For example:

<!DOCTYPE html>
<html>


<head>
	<title>How to Append HTML Code to a Div using JavaScript</title>
	<style>
		body {
			text-align: center;
			font-family:verdana;
			padding: 5%;
		}
		h1{
			color:green;
		}


		button{
			border-radius:5px;
			background-color:cyan;
			outline:none;
		}
	</style>
</head>


<body>
	<div id="first">
		<h1>JavatPoint</h1>
		<p>This is line is always visible to user</p>
	</div>


	<button onclick="doSomeThing()">Add Magic</button>
	<script>
		function doSomeThing() {
			document.getElementById("first").innerHTML +=
			"<h3>This line is presented after clicking the button</h3>";
		}
	</script>
</body>


</html>

Output:

How to append HTML code to a div using JavaScript

Explanation

In the above code, we have a file with HTML, CSS and JavaScript embedded in the same file. We have one div which has id ‘first’. We have one button, and when we click the button, it will run the doSome() method.

Now, if we see the definition of the doSome() method, then we will see we have targeted the div using its id and append the HTML code in string format using double quotes. If we don’t use the double quotes, then it will throw an error.

Whenever we click that button, it will add an h3 element to our tag, which will be displayed on the screen.

Basically, whenever we use the innerHTML attribute, it creates that element again and adds the new HTML code into it and displays it on screen.

2.insertAdjacentHTML() method

Here, we will use the insertAdjacentHTML() method to target the element, and we will put the location where we have to append.

We have four positions:

  1. 1.beforebegin
  2. 2.beforeend
  3. 3.afterbegin
  4. 4.afterend

For example

<!DOCTYPE html>
<html>


<head>
	<title>How to Append HTML Code to a Div using JavaScript</title>
	<style>
		body {
			text-align: center;
			font-family:verdana;
			padding: 5%;
		}
		h1{
			color:green;
		}


		button{
			border-radius:5px;
			background-color:cyan;
			outline:none;
		}
	</style>
</head>


<body>
	<div id="first">
		<div id ="second">
		    <h1 id="heading">JavatPoint</h1>
		  <p id="para">This is line is always visible to user</p>
		</div>
	</div>


	<button onclick="doSomeThing()">Add Magic</button>
	<script>
		function doSomeThing() {
			document.getElementById("second").insertAdjacentHTML('beforebegin',
			"<p>This line is presented after clicking the button and before the starting of second div</p>");


			document.getElementById("second").insertAdjacentHTML('beforeend',
			"<p>This line is presented after clicking the button and before the ending of second div</p>");


			document.getElementById("second").insertAdjacentHTML('afterbegin',
			"<p>This line is presented after clicking the button and just before the JavatPoint</p>");
		
			document.getElementById("second").insertAdjacentHTML('afterend',
			"<p>This line is presented after clicking the after ending the second div </p>");
		}
	</script>
</body>


</html>

Output:

How to append HTML code to a div using JavaScript

Explanation

  • In the above code, we have one div with id as ‘first’, and it has a child div named as ‘second '.
  • In the child div, we have one h1 tag and one p tag. We have one button which will run the function when it is clicked. We have used insertAdjacentHTML four times to try out different positions.
  • The first time we applied it on div second and position is ‘beforebegin’ so it will append the HTML code before the beginning of div named second.
  • In the second time, we applied it on the div second, but this time position is ‘beforeend’. So now it will append the HTML code just before ending the div ‘second’.
  • The third time we applied it on the div second, and now this time position is ‘afterbegin’, which means we can append the HTML code just after the starting of div ‘second’.
  • The last time we applied it on div second, and now the position is ‘afterend’ which means we will be able to append the HTML code just after the ending of div ‘second.’

Related Topics

HTML <samp> tag

The Samp tag in HTML is used for defining the sample output from the computer program. This tag is a phrase type tag and a container tag that means the...

2 minutes read.

What does HTML stand for?

HTML stands for Hyper Text Markup Language. We use this markup language to design a web page. Web browsers use this language to showcase text, videos, images, audio and other...

6 minutes read.

HTML <script> Tag

For embedding a client -side script, we use script tag in html tag. This <script> tag can be used for containing scripting statements. It can also point another external script file...

2 minutes read.

How to insert image in HTML

An image (technically digital image) in HTML or even in general technical aspects is a binary representation of visual information. By visual information we mean, in the form of drawings/pictures,...

5 minutes read.

HTML Youtube

<object> element: It embed the object within the HTML documents and embed plug-ins such as Java applets, PDF readers, Flash Players etc in web pages. Example: <object width="100" height="100" data="bookmark.swf"></object> <embed> element: It defines an embedded...

1 minute read.

HTML Links

It consist of anchor element which is used to create a link between a source anchor and destination anchor. The anchor tag can be embedded between text, image, video or...

2 minutes read.

HTML Date

The input element in HTML has several attributes. One of its attributes is the type attribute which creates a calendar in an order that a user can select a date...

5 minutes read.

HTML Canvas

HTML Canvas: Using JavaScript, the < canvas > tag in HTML is used for drawing graphics on web page. It can be used to draw routes, boxes, text, gradient, and...

3 minutes read.

Design a tribute page using HTML and CSS

A tribute page is a webpage based on a person who inspired us in our life. In this article, we will create a webpage of Mahatma Gandhi. We are going...

5 minutes read.

HTML <section> tag

The section element in HTML is used to define sections in a document. Syntax of Section Tag: <body> <h1>……….</h1> <section> <h2>……….</h2> <p> …………………………</p> </section> <section> <h2>………..</h2> <p>…………………………. <p> </section> </body> Examples of Section Tag Example 1: In this example, we use the HTML "section" element...

3 minutes read.

HTML <video> Tag

The Video tag in HTML is used to play video on a media player on the web page. We can also insert an audio by the video tag, but audio...

6 minutes read.

HTML Headings

The titles and subtitles of our webpages are known as HTML headings. Let’s not talk about webpages but giving heading to almost everything like normal paragraphs, articles or let it...

2 minutes read.

Html Wbr Tag

The Line Break Opportunity element A word break opportunity is a place in text from where the browser breaks a line. This opportunity is represented by the element wbr in the...

2 minutes read.

HTML Frames

Frames in Html is used to divide the browser into different sections where each section can load different Html documents. Collection of frame is known as Frameset. Creating frames:We use frameset...

2 minutes read.

How to change font in HTML

To give style to the content of your website, you may change the font of the text and make your website look attractive to the user. There are several methods which...

4 minutes read.

HTML Anchor

HTML Anchor The HTML anchor tags define a hyperlink that links to other pages on one page. It can create hyperlinks to any web page and files, locations or any other...

3 minutes read.

What is a Container tag?

In HTML, there are different types of tags or say instructions which make the developer specify various elements in the document and make the browsers understand what to display. Tags in...

5 minutes read.

HTML Font Size

The HTML <font> tag uses the size attribute to specify the size of the text. We can set the size attribute’s value from 1 to 7. The default size of...

4 minutes read.

HTML Form Action

The <form> tag has an attribute named action that contains a URL. The HTML action attribute defines the webpage URL on which you want to send the data after submitting...

4 minutes read.

HTML5 Attribute

HTML Attribute HTML attributes are special words that provide additional information about the HTML element or attributes.The element or tags have attributes, which define the element's behavior.It also adds attributes with a start...

3 minutes read.