Skip to content

JavaScript create element with class

  • by

To create an HTML element with a class in JavaScript, you can use the document.createElement() method to create a new element and then add a class to it using the classList.add() method.

To create a new HTML element with a class in JavaScript, you can use the following code:

// Create a new element
const newElement = document.createElement('div');

// Add a class to the element
newElement.classList.add('my-class');

// Add the element to the page
document.body.appendChild(newElement);

JavaScript creates an element with a class example

A simple example code creates a new div element with a class of my-class and appends it to the body of the HTML document using JavaScript:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Creating an element with class in JavaScript</title>
  </head>
  <body>
    <h1>Creating an element with class in JavaScript</h1>

    <script>
      // Create a new element
      const newElement = document.createElement('div');

      // Add a class to the element
      newElement.classList.add('my-class');

      // Add some text content to the element
      newElement.textContent = 'Hello, world!';

      // Add the element to the page
      document.body.appendChild(newElement);
    </script>
  </body>
</html>

Output:

JavaScript create element with class

Alternatively, you can put the JavaScript code in a separate file and include it in your HTML document using a script tag:

<!DOCTYPE html>
<html>
  <head>
    <title>My Web Page</title>
    <script src="my-script.js"></script>
  </head>
  <body>
    <!-- HTML code goes here -->
  </body>
</html>

Comment if you have any doubts or suggestions on this Js basic topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading