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
The 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.org/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.org/en-US/docs/Web/API/Document/createElement
Whether these constructors will be implemented for other elements I don't know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With