9

When i tried to create an instance of DOM's HTMLElement,

var oElement = new HTMLElement();

It throws : TypeError: Illegal constructor

Why can't we instantitate DOM's Constructor Functions ? Is there a way to do it? Thanks

ikiw
  • 372
  • 1
  • 4
  • 17
  • 4
    You cannot create instance of HTML Element in JS directly as all of them falls under document object. Using document object properties however you can create html element. `var element=document.createElement('yourHTMLElement');` – Ankur Aggarwal Apr 18 '14 at 09:10

3 Answers3

13

To create a new element with Javascript you use the createElement method of the document object.

var newDiv = document.createElement("div");

To add some new text with Javascript you can use the createTextNode method of the document object.

var text = document.createTextNode("Text goes here");
Ruslan Ismagilov
  • 1,360
  • 7
  • 14
12
Object.create(HTMLElement.prototype, {})
Martin Wantke
  • 4,287
  • 33
  • 21
7

Most DOM constructors are not supposed to be constructors, but just holders for their prototype interface. They will however have factory functions to construct them, which also validate the arguments.

In your particular case, an HTMLElement does a) need a tagname and b) a document to associate the node with. The createElement method of document takes both.

Lloyd
  • 8,204
  • 2
  • 38
  • 53
Bergi
  • 630,263
  • 148
  • 957
  • 1,375