Yogesh Chauhan's Blog

How to create a new HTML element programmatically using JavaScript?

in HTML & JavaScript on September 25, 2020

We can create a HTML element programmatically using JavaScript.

For example, let’s say we have a body with just header in it.


<body>
 <h1>Adding an element</h1>
</body>

Now, let’s add paragraph in the body.

Step 1: Create an element with createElement() Method


var element = document.createElement('p');

Step 2: Add content in p tag using textContent property.


element.textContent = "Hello, World";

Step 3: Add the newly created element to the DOM.


document.body.appendChild(element);

So, the body will become:


<body>
 <h1>Adding an element</h1>
 <p>Hello, World</p>
</body>

See it in action:


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to detect the Blog Page in WordPress?WordPressHow to Skip or Exclude a Specific URL or File From .htaccess Rewrite Rule?PHPFor Each Loop in Swift for BeginnersSwiftHow to overwrite file contents with new content in PHP?PHPSolution for “Yarn build: Failed because of a stylelint error”WordPressHow to get front page or home page ID in WordPress?WordPressHow to redirect or load a new document using JavaScript?JavaScriptHow to convert a number rounding to a specified number of decimals in JavaScript?JavaScriptCreate a simple bar chart and column chart using pure CSS gridCSSA complete diagram with building blocks of an Angular applicationAngularUseful (and probably ignored) HTML tags: Part 1HTMLHow to get the full URL of current page in PHP?PHP