How to add div element to body or document in JavaScript?

Sometimes, we want to add div element to body or document in JavaScript.

In this article, we’ll look at how to add div element to body or document in JavaScript.

How to add div element to body or document in JavaScript?

To add div element to body or document in JavaScript, we can use the createElement and appendChild methods.

For instance, we write

const elem = document.createElement("div");
elem.style.cssText = `
  position: absolute;
  width: 100%;
  height: 100%;
  opacity: 0.3;
  z-index: 100;
  background: #000;
`;
document.body.appendChild(elem);

to create a div with createElement.

Then we set the CSS styles of the div to

`
  position: absolute;
  width: 100%;
  height: 100%;
  opacity: 0.3;
  z-index: 100;
  background: #000;
`

Then we append the div as a child of the body element woth

document.body.appendChild(elem);

Conclusion

To add div element to body or document in JavaScript, we can use the createElement and appendChild methods.