I am learning how to write object oriented javascript. I have a simple class to create div elements, but when I test the code no new elements are created. Am I doing this correctly? I am using the following code:
function elementCreation(elementParent, elementId, elementText) {
this.elementParent = document.getElementsByTagName(elementParent)[0];
this.elementId = elementId;
this.elementHtml = elementText;
this.elementMake = function (type) {
newElement = document.createElement(type);
// add new element to the dom
this.elementParent.appendChild(newElement);
};
}
var newObject = new elementCreation('body', 'testdiv', 'some text here!!!');
newObject.elementMake('div');
Your code works perfectly, congratulations.
You simply can’t see an empty div without styling.
See here a demonstration with styling :
Note that if your construction parameters were intended for the construction of the child element, you have to put them to some use. For example :
Demonstration
I won’t try to use the
elementIdparameter : if you define a function, it’s probably to call it more than once and an id can’t be used more than once in HTML.