The open blogging platform. Say no to algorithms and paywalls.

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.




Continue Learning