I have created a new element with JavaScript using document.createElement() and I've appended it to the body using document.body.appendChild(). I want to create another element inside of this element inside of this element inside of this element. I know it can be done like this:
var firstElement = document.body.createElement('div');
var secondElement = document.body.cteateElement('div');
firstElement.appendChild(secondElement);
document.body.appendChild(firstElement);
But what if I don't want to append the second element to the first element immediately? What if I want to remove the element at a later time after some event? Wouldn't both elements need an ID?
I've created two functions, one to create the first element and one to create the second. I've then called them both:
function createFirstElement() {
};
function createSecondElement() {
};
createFirstElement();
createSecondElement();
inside of function createFirstElement(), I've created my first element, obviously! I've also styled it, given it an ID and appended it to the body:
function createFirstElement() {
var firstElement = document.createElement('div');
firstElement.id = 'firstElement';
firstElement.style.width = '600px';
firstElement.style.height = '400px';
firstElement.style.backgroundColor = 'red';
document.body.appendChild(firstElement);
};
This function works fine, a red <div> 600x400px is drawn in the browser.
Now with createSecondElement(), I want to add another element inside of this element.
createElementTwo() is basically the same as createElementTwo(), except I want to create a new element inside of element one instead of the body:
function createElementTwo() {
var firstElement = document.getElementById('firstElement');
var elementTwo = document.createElement('div');
elementTwo.id = 'elementTwo';
elementTwo.style.width = '300px';
elementTwo.style.height = '200px';
elementTwo.backgroundColor = 'blue';
firstElement.appendChild(elementTwo);
};
This does not work!
All together my code looks like this:
function init() {
var body = document.body;
function createFirstElement() {
var firstElement = document.createElement('div');
firstElement.id = 'firstElement';
firstElement.style.width = '600px';
firstElement.style.height = '400px';
firstElement.style.backgroundColor = 'red';
body.appendChild(firstElement);
};
function createElementTwo() {
var firstElement = document.getElementById('firstElement');
var elementTwo = document.createElement('div');
elementTwo.id = 'elementTwo';
elementTwo.style.width = '300px';
elementTwo.style.height = '200px';
elementTwo.backgroundColor = 'blue';
firstElement.appendChild(elementTwo);
};
createFirstElement();
createElementTwo();
};
init();
I've searched around online, but all I can find is how to create a new element, or add an element to an element that already exists in the HTML document.
What am I doing wrong?