Oftentimes, we want to add a div element to the body or document of the web page with JavaScript.
In this article, we’ll look at how to add a div element to the body or document with JavaScript.
Set the document.body.innerHTML Property
One way to add a div element to the body
element is to set the document.body.innerHTML
property.
For instance, we can write:
document.body.innerHTML += '<div>hello world</div>';
We assign the innerHTML
to a string with the code for a div element.
Therefore, we’ll see the div rendered in the body.
Call the document.createElement Method
Another way to add a div to the body
element is to use the document.createElement
method.
document.createElement
is used to create the div.
Then we call document.body.appendChild
to append it to the body
element as its child.
For instance, we can write:
const elem = document.createElement('div');
elem.style.cssText = 'position: absolute; width: 100ppx; height: 100px; z-index:100; background: lightgreen';
elem.innerHTML = 'hello world'
document.body.appendChild(elem);
We call document.createElement
to create the div.
Then we set the elem.style.cssText
property to add some styles to the div with CSS.
Next, we assign a value to the innerHTML
property to add some content in the div.
And finally, we call document.body.appendChild
with elem
to add the div to the body as its child.
Conclusion
We can add a div into the body
element of a web page by assigning an HTML string to the document.body.innerHTML
property.
Or we can create a div element with document.createElement
and call document.body.appendChild
with the created div.