最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why can you use new Image but not new Div or new Span? - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 10

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/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:

  1. HTMLImageElement has constructor as Image(), so it allows new Image()
  2. HTMLDivElement has no constructor

source:

https://developer.mozilla/en-US/docs/Web/API/HTMLImageElement https://developer.mozilla/en-US/docs/Web/API/HTMLDivElement

发布评论

评论列表(0)

  1. 暂无评论