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?
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
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!
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);