7

I know we can use
const a = document.createElement('a').

But what I'm trying is
const a = new HTMLAnchorElement()

However this will throw the following Exception :
Uncaught TypeError: Illegal constructor

What am I doing wrong ?

vdegenne
  • 12,272
  • 14
  • 80
  • 106
  • Where is `HTMLElement` extended at code at Question? Why are you trying to create an element using `HTMLAnchorElement`? – guest271314 Sep 23 '17 at 04:55
  • @guest271314 According to the specs, `HTMLAnchorElement` extends `HTMLElement` (`HTMLAnchorElement.prototype = new HTMLElement();`). Using an anchor in my post is to provide an example. I don't know it feels more right. – vdegenne Sep 23 '17 at 04:58
  • Not gathering what you are trying to achieve? – guest271314 Sep 23 '17 at 05:02
  • 2
    @guest271314 really, there is no background to my question, I simply try to understand why trying to instantiate an HTMLElement won't work (because every HTML elements that can be bind to the dom are based on it) and I try to understand the behavior behind it, as I said it feels more right. – vdegenne Sep 23 '17 at 05:06
  • Speaking of ‘feel’, I’ve always had the impression that the new keyword is loathed. –  Sep 23 '17 at 05:31
  • 1
    Possible duplicate of [Instantiating new HTMLElement in TypeScript](https://stackoverflow.com/questions/26220243/instantiating-new-htmlelement-in-typescript) – Dinh Tran Sep 23 '17 at 05:32
  • Are you trying to use web components to create a custom element? – guest271314 Sep 23 '17 at 06:06
  • @guest271314 yes but this post has nothing to do with custom elements I think. – vdegenne Sep 23 '17 at 07:54
  • If custom elements is not within the scope of the inquiry is the question essentially why `Uncaught TypeError: Illegal constructor` is thrown when trying to call `new HTMLAnchorElement()`? – guest271314 Sep 23 '17 at 07:57
  • @guest271314 yes but it is just not about `HTMLAnchorElement`, this exception is thrown on all the HTMLElement extended classes. I just pick one example. Also when creating a custom element we extend the HTMLElement base class and then we can use `new MyElement` to make one instance and append it in the dom, it will work. My question is *why won't that work using the native extended classes ?* – vdegenne Sep 23 '17 at 08:01
  • 1
    If you have read the [specification](https://html.spec.whatwg.org/multipage/dom.html#htmlconstructor) and not located the answer to your inquiry, consider filing an [issue](https://github.com/whatwg/html/issues) to attempt to get definitive clarification as to your question relevant to the current text of the specification. – guest271314 Sep 23 '17 at 08:21

0 Answers0