Hi everyone, I'm Kasong.
According to the ES specification , all non-primitive objects converted to
Boolean
are all true
:
But here is a special case: document.all
This article will talk about this cold knowledge.
The role of document.all
document.all
will return a HTMLAllCollection
collection, including all nodes under document
It can be understood as a containing all DOM nodes in the page :
Early web
developers used the API
obtain the DOM node, such as:
// 获取页面中第一个节点,即HTML
document.all[0];
// 获取页面中id为"abcd"的节点
document.all["abcd"];
With the WEB
, its role has been gradually replaced by other methods of document
- getElementById
- querySelector
......
W3C
forward with weight
Although there is a better API
, but many old pages are still using document.all
. How to make a better transition?
For compatibility, many developers will write the following code:
if (document.all) {
// 老浏览器
} else if (document.getElementById) {
// 支持getElementById的现代浏览器
}
The problem is that many modern browsers also implement document.all
, which allows the code to enter the old in all browsers.
From June to October 2009, there were as many as 56 messages on the W3C mailing list document.all
The final result of the discussion is: In modern browsers, document.all
transformed into Boolean
the result is false
.
In this way, the above code will not enter the logic of old browser
Summarize
In addition to the above characteristics, document.all
also has some characteristics different from ordinary people, such as:
- When used as
==
and!=
operators, it will be treated asundefined
typeof document.all === 'undefined'
These weird results are for browser backward compatibility. Although many modern browsers support document.all
, it has been removed from the standard.
I can think of his only role at the moment, which is probably to challenge the interviewer...
Welcome to join human high-quality front-end framework group , take flight
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。