How to create HTML elements with ID and class using JavaScript?
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

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress? Mar 3 substring() Method in JavaScript Mar 3 Window setInterval() Method in JavaScript Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS

You might also like these

Some SQL LIKE Operators We Need to Keep in MindSQL/MySQLWP_Query Class in WordPressWordPressThe Difference Between Arrays and Objects in JavaScriptJavaScriptCSS Attribute SelectorsCSSHow to solve “framework not found” error in Swift?SwiftHow to Draw a Text Image using JavaScript?JavaScriptHow to create a link tag button using CSS?CSSWhat Is a Graph Database?Misc12 URLSearchParams methods in JavaScriptJavaScriptSELF JOIN in PostgresPostgresThe Differences Between HAVING Clause and WHERE Clause in SQLSQL/MySQLHow to import a CSS file using PHP code and not HTML code?PHP