YogeshChauhan . com

How to create HTML elements with ID and class using JavaScript?

in HTML & JavaScript on February 13, 2021

In this JavaScript post, I demonstrated how to create HTML elements using JavaScript.

But many times, we need to create elements with class and id attributes so that we can target those newly created elements.

We can use setAttribute() Method to set id and class attributes.

setAttribute() Method

This method adds the defined attribute to an HTML element, and also adds a defined value to it.

For e.g. we can set background-color of an element like this:

el.setAttribute("style", "background-color: green;");

createElement with id

You will be able to see it using inspect element in any browser.

createElement with id

createElement with class

The same way we can set the class. Just like this:

You will be able to see it using inspect element in any browser.

createElement with id and class

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

WordPress 5.7 is migrating to latest jQuery version and people are freaking outjQuery4 different Ways to Get JavaScript OutputJavaScript2 Ways We Can Write Multiple Line Commands in PHPPHPHow to disable right click and drag and drop of images using jQuery?jQueryHow to Pop an Alert Box in PHP?JavaScriptKanban vs Scrum: The two frameworks of agile principlesMiscHow to enable and disable button using JavaScript?JavaScriptHow to Use ROLLUP Operator in SQL and MySQL?SQL/MySQLWhat happened to your Google Analytics Tracking ID, can’t find it?MiscHow services and dependency injection work in Angular?AngularMicroservices vs Monolithic ArchitectureMiscCreate a currency (dollar) to coins convertor in ReactReact