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 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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

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
PHP Variables ScopePHPAll possible ways you can Insert Data in PostgresPostgresObject destructuring in JavaScript: Unpacking fields from objects passed as function parameterJavaScriptThe simple difference between var, let and const in JavascriptJavaScriptHow to scroll contents of a an element vertically using JavaScript?JavaScriptSQL Right JoinSQL/MySQLWordPress: How to display fields from ACF Flexible Contents?WordPressWordPress: How to print ACF repeater field values?WordPressHow to add and remove list items using JavaScript?JavaScriptWordPress: How to add a Search Icon in Menus with toggle effect using jQuery?jQueryComponents and Props in ReactReactHow states work in React?React