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
How to display modal from bottom to top using CSS and JavaScript?CSSWindow innerHeight and innerWidth properties in JavaScriptJavaScriptWill SQL (Relational) Database become obsolete?SQL/MySQLWordPress: How to print ACF repeater field values?WordPressHow to control file extensions with an .htaccess file?MiscellaneousHow to reprocess failed items in Etrieve Flow?MiscellaneousThe Difference Between Arrays and Objects in JavaScriptJavaScriptWordPress: How to display slider repeater fields in ACF?WordPressHow to make HTML form interactive and using CSS?CSSFunction Scope in JavaScript for BeginnersJavaScriptA Quick Guide to Object-Oriented Programming in PHPPHPIntroduction to components and templates Part 4: Pipes and DirectivesAngular