On many occasions, we want to create and style div elements in our web app dynamically.
In this article, we'll look at how to create and style a div using JavaScript.
Using the document.createElement Method
We can create an HTML element using theĀ document.createElement
Ā method.
To use it, we just pass in the tag name of the element we want to create as a string.
For instance, we can write:
const div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello";
document.body.appendChild(div);
to create a div, style it, and append it as the child of theĀ body
Ā element.
createElement
Ā returns the element object.
Then we can set the properties of theĀ style
Ā property to apply various styles.
All the CSS properties are in camel case in theĀ style
Ā property.
innerHTML
Ā sets the content of the HTML element.
Set the innerHTML Property of document.body
We can also set theĀ innerHTML
Ā property ofĀ document.body
Ā to a string with HTML code to add content to theĀ body
Ā element.
For example, we can write:
const div = "<div>hello</div>";
document.body.innerHTML = div;
to set theĀ innerHTML
Ā property of the div to what we want.
Conclusion
We can create a div by using theĀ document.createElement
Ā method.
Then we can style it by assigning values to the properties of theĀ style
Ā property.