Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *