I am working on a project, and am required to build HTML code dynamically.
I've got this code in main.js:
function main() {
this.dashboard = new Layer("dashboard");
this.dashboard.addText("Hello, World!");
this.newLayer = new Layer("somelayer");
this.anotherLayer = new Layer("somenewlayer");
this.newLayer.addText('testing...');
this.newLayer.addLayer(anotherLayer);
this.dashboard.addLayer(newLayer);
this.dashboard.update();
$("#wrapper").html('');
$("#wrapper").append(this.dashboard.getElement());
}
The function main is called once the body is loaded.
I also have a layer.js file with the following code:
function Layer(id) {
this.id = id;
this.children = [];
this.el = null;
}
Layer.prototype.addText = function(text) {
this.children.push(text);
}
Layer.prototype.addLayer = function(l) {
this.children.push(l);
}
Layer.prototype.getElement = function() {
return this.el;
}
Layer.prototype.update = function() {
this.el = document.createElement('div');
this.el.className += " layer";
for (var i = 0; i < this.children.length; i++) {
child = this.children[i];
alert('child (' + child + ') is...');
if(typeof child === 'string') {
alert('...a string');
txt = document.createTextNode(child);
this.el.appendChild(txt);
} else {
alert('...not a string');
child.update();
this.el.appendChild(child.getElement());
}
alert('um kyankst');
}
}
This is used, so that I can dynamically create layers and add text, or more layers to them. After I call update, it should convert it into HTML.
Using the following HTML...
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles/styles.css".>
<script src="scripts/jQuery.min.js"></script>
<script src="scripts/main.js"></script>
<script src="scripts/layer.js"></script>
</head>
<body onload=main()>
<div id="wrapper"></div>
</body>
</html>
I get nearly the result I am looking for--a DIV, and inside it there is some text saying "Hello, World", and then another DIV.
However, inside the other DIV I have added the text 'testing...' and another layer/DIV, but it doesn't seem to be showing up.
Does anyone know why this is happening?