How can I create and style a div using JavaScript?
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?
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
.
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!