How to add a class when creating a div

How to add a class when creating a div element

Posted by Ervin Adams on August 7, 2022

How to add a class when creating a div

How to add a class when creating a div element

Posted by Ervin Adams on August 7, 2022

Here is how you add a class to an element such as a div.

Step 1 Create the div element using create.document() method

Step 2. Use the classlist.add() method to add the class or classes to the div

Step 3. Use appendChild() method to add div element to parent div

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wecode101 add class when creating div element</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
  <main>
    <!--Main layout-->
    <div class="container" id="ctn"></div>
  </main>
</body>
</html>

JS

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

div.classList.add('col-9', 'mx-auto', 'fs-2'); //Add classes to element

div.textContent = 'The Title'; //Add text element 

const container = document.getElementById('ctn'); //Identify element to add div

container.appendChild(div); // Add div to to element