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.

 <h1>Adding an element</h1>

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.


So, the body will become:

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

See it in action:

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
JavaScript: how to detect a browser using the user agent?JavaScriptConditional operator in JavaScript (aka ternary operator)JavaScriptA Quick Guide to Object-Oriented Programming in PHPPHPThe flex-grow, flex-shrink and flex-basis Properties in CSSCSSUse inline if to make a shorter conditional syntax in ReactReactHow to create a Bootstrap style accordion using CSS and JavaScript?CSSThe difference between Class declarations and Class expressions in JavaScriptJavaScriptHow to scroll contents of HTML body horizontally and vertically using JavaScript?JavaScriptHow to convert an HTML radio buttons into a toggle switch using CSS?CSSHow to create a dynamic countdown using HTML and JavaScript?HTMLHow to add transparent text on top of an image using CSS?CSSHow to show confirmation alerts with OK and cancel buttons using Swift 5?Swift