Reputation: 2643
I want to make a constructor function that creates a documentElement object.
As an example, consider the new Audio() constructor - it creates a documentElement object, and if you pass it some variables it populates the new documentElement with attributes. It doesn't insert it into the DOM, it simply creates the object.
So, the question is - what makes a documentElement different from a vanilla javascript object (of the {property: value} kind), and can you write constructors for them like you can for objects?
Edit:
What I'm toying with is re-creating the new Audio() constructor in browsers that don't have it, using a quicktime or flash HTMLObjectElement in place of the HTMLAudioElement.
It's ok with me that audio.constructor will refer to HTMLObjectElement, as the result of using new Audio() in browsers that support it, is that audio.constructor refers to HTMLAudioElement.
I'm not sure about the Audio.prototype. When I query console.log(Audio.prototype) in browsers with Audio support, they return nothing at all - not even an empty line in console.log - so that's got me stumped. If I understand right, though, it doesn't affect what I'm aiming to do.
The aim is to be able to code using the Audio constructor, and have the browser handle it natively or set up a plugin instance if it needs to.
Upvotes: 3
Views: 6271
Reputation: 827862
The document element is not a plain JavaScript object, is a DOM Element object, that implements the general DOM Core document interface.
You can create documentElements by using document.implementation.createDocument (available from DOM Core Level 2):
function createDocument() {
var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml',
'html', null),
body = document.createElementNS('http://www.w3.org/1999/xhtml', 'body');
doc.documentElement.appendChild(body);
return doc;
}
Edit:
Do you mean something like this?
function ElementCreator(tagName, attributes){
this.element = document.createElement(tagName);
for (var i in attributes) {
this.element[i] = attributes[i];
}
return this.element;
}
var anchor = new ElementCreator('a', { id: 'myLink', href:'http://google.com',
innerHTML:'Link text' });
document.body.appendChild(anchor);
// <a id="myLink" href="http://google.com">Link text</a>
However I don't see too much advantage of using a constructor function for that.
The element is returned from the constructor function, the object instance
is lost, anchor.constructor
in the above example refers to HTMLAnchorElement
instead of ElementCreator
, and for that the access to the ElementCreator.prototype
is also lost.
It would make more sense if the DOM Element instance is wrapped on a member, or just implement a simple function.
Upvotes: 6