In examples I've seen new Image()
to create a new HTML image element but when I try new Div()
there is no support. Is there a reason for this or any plan in the future to add it?
Example:
var image = new Image();
var div = new Div(); // error
In examples I've seen new Image()
to create a new HTML image element but when I try new Div()
there is no support. Is there a reason for this or any plan in the future to add it?
Example:
var image = new Image();
var div = new Div(); // error
Share
Improve this question
asked Jan 27, 2018 at 7:11
1.21 gigawatts1.21 gigawatts
17.9k40 gold badges143 silver badges271 bronze badges
2
-
This is just a guess. Images are plete in and of themselves. There is no such thing as
<img>Suff</img>
.<div>
on the other hand is almost always a container for something else. – James A Mohler Commented Jan 27, 2018 at 7:16 - @James A Mohler: Why would it make sense for a void element to have a unique constructor and simultaneously not make sense for a non-void element to have one? – BoltClock Commented Jan 27, 2018 at 8:16
3 Answers
Reset to default 10The Div
class doesn't exist. Any DOM Element can be created using the function Document.createElement()
:
var div = document.createElement('div');
var img = document.createElement('img');
document.createElement('div')
creates a new HTMLDivElement
.
new Image()
creates in fact an HTMLImageElement
and is equivalent to document.createElement('img')
.
Images can be created using the new Image()
syntax for historical reasons. Back in the 90s, the Image
object has been one of the first dynamic HTML feature implemented by all browsers before the current DOM was even invented (not to mention implemented the same way by all browsers).
It's a good question why that method exists. The HTML Living Standard doesn't answer that question (https://html.spec.whatwg/multipage/embedded-content.html#dom-image). It just states there is a constructor for HTMLImageElements provided in addition to the factory method
document.createElement('img')
With this function you can create all DOM elements, e.g.
document.createElement('div')
https://developer.mozilla/en-US/docs/Web/API/Document/createElement
Whether these constructors will be implemented for other elements I don't know.
My Google search concluded that you are using Web Api
It may also be due to existence of constructor:
- HTMLImageElement has constructor as Image(), so it allows new Image()
- HTMLDivElement has no constructor
source:
https://developer.mozilla/en-US/docs/Web/API/HTMLImageElement https://developer.mozilla/en-US/docs/Web/API/HTMLDivElement