YogeshChauhan . com

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 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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to Validate User Name, Email Address and URL in PHP?PHPWhat is Hadoop and Hadoop Ecosystem?MiscRendering Elements in ReactReactWhat is Hoisting in JavaScript?JavaScriptHow to Pop an Alert Box in PHP?JavaScriptThe Difference Between Arrays and Objects in JavaScriptJavaScriptSolution to Precision Problem in JavaScript NumbersJavaScriptHow to add recaptcha version 3 to PHP website?PHPA Quick Guide to Object-Oriented Programming in PHPPHPWhat’s a page re-rendering in React?ReactHow to get the full URL of current page in PHP?PHPSolution to “NullInjectorError: No provider for module” in Angular 9Angular