Yogesh Chauhan's Blog

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 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
How To Create a Fullscreen Background Video using CSS and JavaScript?CSSThe Difference Between isNaN() Method And isNaN() Function In JavaScriptJavaScriptHow to Validate User Name, Email Address and URL in PHP?PHPHow to create a Bootstrap style accordion using CSS and JavaScript?CSSWill SQL (Relational) Database become obsolete?SQL/MySQLHow to make a web page look good on any device?HTMLDifferent Types of Functions in JavaScriptJavaScriptAll possible ways you can Insert Data in PostgresPostgresHow to progressively load images and add a blurry placeholder?CSSWhat are “holes” in a React component?ReactWhat’s the difference between variables in CSS and SCSS (Sass)?CSSHow to obfuscate JavaScript code to hide it from View Source?JavaScript