Adding a new div and giving it a class name
Here are a few ways to add a new div
element and give it a class name:
Method 1: Using the document.createElement
method
const newDiv = document.createElement('div');
newDiv.className = 'my-new-class';
document.body.appendChild(newDiv);
Method 2: Using the innerHTML
property
const newDiv = document.createElement('div');
newDiv.innerHTML = '';
newDiv.className = 'my-new-class';
document.body.appendChild(newDiv);
Method 3: Using the createElement
method with a string
const newDiv = document.createElement('<div class="my-new-class"></div>');
document.body.appendChild(newDiv);
Method 4: Using a template literal
const newDiv = document.createElement(`div`);
newDiv.className = 'my-new-class';
document.body.appendChild(newDiv);
In all cases, the newDiv
variable will reference the newly created div
element with the class name my-new-class
. You can then append it to the document.body
element to add it to the page.
Note that in the first two methods, we create a new div
element using document.createElement
, and then set its className
property to the desired class name. In the third method, we create a new div
element using a string, which includes the class name. In the fourth method, we use a template literal to create the div
element and set its class name.