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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

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
Social Media Colors: LESS VariablesMiscellaneousHow to change the style for checked radio button or checkboxes using CSS?CSSHow to add and remove list items using JavaScript?JavaScriptThe SQL EXISTS OperatorSQL/MySQLSolution to Could not cast value of type ‘NSTaggedPointerString’ to ‘NSNumber’SwiftHow to add a scroll back to top button using JavaScript and CSS?CSSWhat’s the difference between a Framework and a Library?Miscellaneousrandom function in SCSS (Sass)SCSSWhy does MOV matter in IT or any kind of projects?MiscellaneousAlternate Style Sheets in CSSCSSCheck If a String Contains a Specific Word in PHPPHPHow to disable right click and drag and drop of images using jQuery?jQuery