How to Create Div Element in JavaScript
-
Use the
document.createElement()
Method in JavaScript -
Use
document.body.innerHTML
to Change Property in JavaScript
We frequently need to dynamically build and customize div elements in our web app. We’ll use JavaScript to construct and customize a div in this tutorial.
Use the document.createElement()
Method in JavaScript
Using the document.createElement, we may create an HTML element. createElement is a technique for creating elements.
We supply the tag name of the element we wish to build as a string to use it.
Example Code:
const div = document.createElement('div');
div.style.width = '60px';
div.style.height = '20px';
div.style.background = 'green';
div.style.color = 'white';
div.innerHTML = 'Upwork';
document.body.appendChild(div);
Output:
Style it and attach it to the body
element as a child to make a div. The element object is returned by createElement.
The style
property’s properties can then be set to apply various styles.
In the style property, all CSS properties are in the camel case. The HTML element’s content is set via innerHTML
.
Use document.body.innerHTML
to Change Property in JavaScript
We can also change the document’s innerHTML
property. To add content to the body element, convert the body to a string with HTML code.
Example Code:
const div = '<div>Upwork</div>';
document.body.innerHTML = div;
Output:
The document.createElement
is a technique for creating elements. using it, we can make a div. Then we can style it by setting values for the style
property’s properties.
Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.
LinkedIn