Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
HTML DOM div object
The HTML DOM div object is associated with the HTML <div> element. Div is a general purpose block level element that allows us to group elements together to either apply style to them or to manipulate a group of HTML elements under a single tag name or id.
Properties
Following is the property for div object −
| Property | Description |
|---|---|
| Align | To set or return the align attribute value of the <div> element. This property is not supported in HTML5 use css instead for aligning. |
Syntax
Following is the syntax for −
Creating a div object −
var p = document.createElement("DIV");
Example
Let us look at an example for the HTML DOM div object −
<!DOCTYPE html>
<html>
<body>
<h2>Div object example</h2>
<p>click on the CREATE button to create a div element with some text in it.</p>
<button onclick="createDiv()">CREATE</button>
<script>
function createDiv() {
var d = document.createElement("DIV");
var txt = document.createTextNode("Sample Div element");
d.setAttribute("style", "margin:10px;width:200px;background-color: lightgreen;border:2px solid blue");
d.appendChild(txt);
document.body.appendChild(d);
}
</script>
</body>
</html>
Output
This will produce the following output −

On clicking the CREATE button −

In the above example −
We have first created a button CREATE that will execute the createDiv() method when clicked by the user −
<button onclick="createDiv()">CREATE</button>
The createDiv() function creates a <div> element and assigns it to the variable d. It then creates a text node and assigns it to the variable txt. We then set the <div> element attributes using the setAttribute() method. The text node is then appended to the <div> element using the appendChild() method. The <div> element along with the text node is then appended as the document body child −
function createDiv() {
var d = document.createElement("DIV");
var txt = document.createTextNode("Sample Div element");
d.setAttribute("style", "margin:10px;width:200px;background-color: lightgreen;border:2px solid blue");
d.appendChild(txt);
document.body.appendChild(d);
}