YogeshChauhan.com

How to create a new HTML element programmatically using JavaScript?

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:

dreamhost

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 uninstall Cocoapods from the Mac OS? #4 How to Use SQL MAX() Function with Dates? #5 How to add Read More Read Less Button using JavaScript? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Apr 7 Solution for “Yarn build: Failed because of a stylelint error” Apr 7 Make sure your links have descriptive text Apr 7 How to add Laravel to WordPress using Sage theme (and install Tailwind CSS)? Apr 2 How to create a sidebar using pure CSS? Apr 1 How to switch dark and light themes using pure CSS? Apr 1 How to calculate elapsed time in JavaScript?

You might also like these

What happened to your Google Analytics Tracking ID, can’t find it?MiscCurrencyPipe in Angular 9 with ExamplesAngularHow to Make CSS Lists Bullets Smaller?CSSSocial Media Colors: LESS VariablesMiscWhat does it mean by Continuous Integration, Continuous Delivery and Continuous Deployment?Misc:in-range and :out-of-range selector in CSSCSSShould we ever delete data from a database?MiscSQL ANY OperatorSQL/MySQLHow to Sort (Shuffle) an Array in Random Order in JavaScript?JavaScriptSQL Right JoinSQL/MySQLWordPress 5.7 is migrating to latest jQuery version and people are freaking outjQueryHow to uninstall Cocoapods from the Mac OS?Misc