Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you use new Image but not new Div or new Span?

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
like image 634
1.21 gigawatts Avatar asked Jan 27 '18 07:01

1.21 gigawatts


2 Answers

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).

like image 57
axiac Avatar answered Oct 20 '22 00:10

axiac


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.

like image 23
Jost Avatar answered Oct 20 '22 00:10

Jost