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 Commit and Rollback Changes in SQL?SQL/MySQLWhat are keys in React?ReactHow to add Laravel to WordPress using Sage theme (and install Tailwind CSS)?PHPDebugging in WordPress Part 2: WP_DEBUG_LOG and WP_DEBUG_DISPLAYWordPressLearn to create your skill bar using CSSCSSHow to overwrite file contents with new content in PHP?PHPContainers 101: What are containers?MiscellaneousHow to add a ribbon inside a container using CSS?CSS@mixin and @include in SCSS (Sass)SCSSHow to get the full URL of current page in PHP?PHPFive common features of Angular template syntax (with examples)AngularFlash of Invisible Text and Mitt Romney Web Font ProblemCSS