How to Create and Style a div Using JavaScript?

ā€¢

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.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics