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 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 replace HTML lists using CSS Counters?CSSKilling A Project Part 4: What Would Be Your Top 3 Priorities For Planning The Cancellation?MiscellaneousThe Lending Club Analysis using Logistic Regression and Random Forest in RStudioMiscellaneousLEFT JOIN in PostgresPostgresThe actual difference between indexOf() and search() in JavaScriptJavaScriptArguments in @mixin rules in SCSS (Sass)SCSSHow to get Current Hour, Minute and Second in JavaScript?JavaScriptQuick Introduction to 11 Array Iteration Methods in JavaScriptJavaScriptSome EASY-to-Understand CSS media query examplesCSSHow to add Google Static Map using ACF map field?WordPressHow to get front page or home page ID in WordPress?WordPressHow to create a circle that follows a cursor using JavaScript and CSS?CSS