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

1
  • 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'); Commented Apr 18, 2014 at 9:10

3 Answers 3

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");
11
Object.create(HTMLElement.prototype, {})
1
  • 2
    This answer is missing its educational explanation. Commented Mar 26, 2022 at 1:13
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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.