How can I use JavaScript to create and style (and append to the page) a div, with content? I know it's possible, but how?
-
See also http://stackoverflow.com/questions/5927012/javascript-createelement-style-problem – Cees Timmerman Nov 14 '14 at 11:15
11 Answers
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello";
document.getElementById("main").appendChild(div);
<body>
<div id="main"></div>
</body>
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello";
document.getElementById("main").appendChild(div);
OR
document.body.appendChild(div);
Use parent reference instead of document.body
.

- 1,689
- 3
- 23
- 36

- 16,230
- 5
- 50
- 56
-
I know this is old but adding a class and related CSS would be a more modern approach, but that is a different question. – Mark Schultheiss Sep 17 '19 at 11:41
-
In my case, setting the element dimensions wasn't working because I forgot to append the unit to my numeric values. With `const width = 100`, I had to write `el.style.width = \`${width}px\`` instead of just `el.style.width = width`. – Gustavo Straube Sep 12 '22 at 21:37
Depends on how you're doing it. Pure javascript:
var div = document.createElement('div');
div.innerHTML = "my <b>new</b> skill - <large>DOM maniuplation!</large>";
// set style
div.style.color = 'red';
// better to use CSS though - just set class
div.setAttribute('class', 'myclass'); // and make sure myclass has some styles in css
document.body.appendChild(div);
Doing the same using jquery is embarrassingly easy:
$('body')
.append('my DOM manupulation skills dont seem like a big deal when using jquery')
.css('color', 'red').addClass('myclass');
Cheers!

- 25,975
- 33
- 97
- 127
-
4I wouldn't say jQuery is easier, it's mostly just shorter. But, instead of using setAttribute for the class, I would use div.className = 'myclass'; – Daan Wilmer Jul 27 '11 at 07:59
-
4jQuery is a LOT easier once you start developing heavy javascript UIs. given that it embraces the functional model of programming from the get go, it makes your code look and behave functional as well. Case in point: ajax using native js vs jquery :) – jrharshath Jul 27 '11 at 16:24
-
4Calling jQuery "functional" is a major stretch. How do you define the functional model, and in what way do you think jQuery embraces it? – Oct 15 '14 at 16:44
-
jquery is great if you have 10 lines in your application. Welcome to hell if you build a serious application with it. Brevity isnt automatically good programming/ – Hal50000 Oct 13 '16 at 00:49
-
1the jQuery portion here does not append a `div` so does not answer the question – Mark Schultheiss Sep 17 '19 at 11:45
While other answers here work, I notice you asked for a div with content. So here's my version with extra content. JSFiddle link at the bottom.
JavaScript (with comments):
// Creating a div element
var divElement = document.createElement("Div");
divElement.id = "divID";
// Styling it
divElement.style.textAlign = "center";
divElement.style.fontWeight = "bold";
divElement.style.fontSize = "smaller";
divElement.style.paddingTop = "15px";
// Adding a paragraph to it
var paragraph = document.createElement("P");
var text = document.createTextNode("Another paragraph, yay! This one will be styled different from the rest since we styled the DIV we specifically created.");
paragraph.appendChild(text);
divElement.appendChild(paragraph);
// Adding a button, cause why not!
var button = document.createElement("Button");
var textForButton = document.createTextNode("Release the alert");
button.appendChild(textForButton);
button.addEventListener("click", function(){
alert("Hi!");
});
divElement.appendChild(button);
// Appending the div element to body
document.getElementsByTagName("body")[0].appendChild(divElement);
HTML:
<body>
<h1>Title</h1>
<p>This is a paragraph. Well, kind of.</p>
</body>
CSS:
h1 { color: #333333; font-family: 'Bitter', serif; font-size: 50px; font-weight: normal; line-height: 54px; margin: 0 0 54px; }
p { color: #333333; font-family: Georgia, serif; font-size: 18px; line-height: 28px; margin: 0 0 28px; }
Note: CSS lines borrowed from Ratal Tomal

- 1,049
- 12
- 15
this solution uses the jquery library
$('#elementId').append("<div class='classname'>content</div>");
Another thing I like to do is creating an object and then looping thru the object and setting the styles like that because it can be tedious writing every single style one by one.
var bookStyles = {
color: "red",
backgroundColor: "blue",
height: "300px",
width: "200px"
};
let div = document.createElement("div");
for (let style in bookStyles) {
div.style[style] = bookStyles[style];
}
body.appendChild(div);

- 61
- 1
- 1
This will be inside a function or script tag with custom CSS with classname as Custom
var board = document.createElement('div');
board.className = "Custom";
board.innerHTML = "your data";
console.log(count);
document.getElementById('notification').appendChild(board);

- 3,533
- 16
- 44
- 45

- 59
- 1
- 2
Here's one solution that I'd use:
var div = '<div id="yourId" class="yourClass" yourAttribute="yourAttributeValue">blah</div>';
If you wanted the attribute and/or attribute values to be based on variables:
var id = "hello";
var classAttr = "class";
var div = '<div id='+id+' '+classAttr+'="world" >Blah</div>';
Then, to append to the body:
document.getElementsByTagName("body").innerHTML = div;
Easy as pie.

- 373
- 3
- 10
-
-
1We need to specify `[0]` when using `getElementsByTagName()`. (Too short for a edit) – HKJeffer Sep 13 '19 at 05:49
create div with id name
var divCreator=function (id){
newElement=document.createElement("div");
newNode=document.body.appendChild(newElement);
newNode.setAttribute("id",id);
}
add text to div
var textAdder = function(id, text) {
target = document.getElementById(id)
target.appendChild(document.createTextNode(text));
}
test code
divCreator("div1");
textAdder("div1", "this is paragraph 1");
output
this is paragraph 1

- 129
- 2
- 3
You can create like this
board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;"
document.getElementById("main").appendChild(board);
Complete Runnable Snippet:
var board;
board= document.createElement("div");
board.id = "mainBoard";
board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;"
document.getElementById("main").appendChild(board);
<body>
<div id="main"></div>
</body>

- 1,689
- 3
- 23
- 36
Here's a small example that uses some nifty reusable DOM utility functions:
// DOM utility functions:
const
elNew = (tag, prop) => Object.assign(document.createElement(tag), prop),
els = (sel, par) => (par ?? document).querySelectorAll(sel),
el = (sel, par) => (par ?? document).querySelector(sel);
// Task:
const elItem = elNew("div", {
className: "item",
textContent: "Hello, World!",
onclick() {
console.log(this.textContent);
},
style: `
font-size: 2em;
color: brown;
background: gold;
`
});
// Append it
el("body").append(elItem);
Additionally, you can also add styles to your element using Object.assign() like:
// Utility functions
const css = (el, styles) => Object.assign(el.style, styles);
// Example:
css(elItem, { color: "blue", padding: "1rem" });

- 196,159
- 39
- 305
- 313
You can just use the method below:
document.write()
It is very simple, in the doc below I explain
document.write("<div class='div'>Some content inside the div (It is styled!)</div>")
.div {
background-color: red;
padding: 5px;
color: #fff;
font-family: Arial;
cursor: pointer;
}
.div:hover {
background-color: blue;
padding: 10px;
}
.div:hover:before {
content: 'Hover! ';
}
.div:active {
background-color: green;
padding: 15px;
}
.div:active:after {
content: ' Active! or clicked...';
}
<p>Below or above well show the div</p>
<p>Try pointing hover it and clicking on it. Those are tha styles aplayed. The text and background color changes.</p>

- 1,159
- 15
- 29