Search code examples
javascripthtmlw3c

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

Solution

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