JavaScript: Can a constructor function create a documentElement object?

I want to create a constructor that creates a documentElement object.

As an example, consider the new constructor Audio () - it creates a documentElement object, and if you pass some variables to it, it will fill the new documentElement with attributes. It doesn't insert it into the DOM, it just creates an object.

So the question is, what makes documentElement different from a vanilla javascript object (of type {property: value}) and you can write constructors for it, how can you for objects?

Edit:

What I'm working with is recreating the new Audio () constructor in browsers that don't have it, using a quicktime element or flash HTMLObjectElement instead of HTMLAudioElement.

It's good that audio.constructor will refer to HTMLObjectElement, since as a result of using the new Audio () in browsers that support it, this is what audio.constructor is referring to HTMLAudioElement.

I'm not sure about Audio.prototype. When I query console.log (Audio.prototype) on audio-enabled browsers, they don't return anything - not even an empty line in console.log - so I was stumped. If I understand correctly, this does not affect what I intend to do.

The goal is to be able to encode using the Audio constructor, and have the browser handle it natively, or configure a plugin instance if needed.

+2


source to share


1 answer


The document element is not a simple JavaScript object, it is a DOM Element that implements the general DOM Core document interface ...

You can create documentElements using document.implementation.createDocument ( DOM Core Level 2 available ):

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 many benefits of using a constructor function to do this.

The item is returned from the constructor function, the object is instance

lost, anchor.constructor

in the above example refers to HTMLAnchorElement

instead of ElementCreator

, and for that access to is ElementCreator.prototype

also lost.

It would make more sense if the DOM Element instance is wrapped in a member or just implements a simple function.

+5


source







All Articles