Hello, everyone. I am Karsong.
According to the ES specification, all objects that are not primitives are converted to Boolean as true:
But there is an exception here: document.all
This article will talk about this cold knowledge.
The role of the document. All
Document. all returns an HTMLAllCollection containing all the nodes under Document. Can be understood as a collection of all DOM nodes in a page:
Early Web developers used this API to get DOM nodes, such as:
// Get the first node in the page, the HTML
document.all[0];
// Get the node whose id is "abcd" on the page
document.all["abcd"];
Copy the code
With the development of the WEB, its role has been gradually replaced by other methods of document, such as:
-
getElementById
-
querySelector
.
Carrying a heavy loadW3C
Despite better apis, many older pages still use Document.all. How to make a better transition?
For compatibility, many developers write code like this:
if (document.all) {
// Old browser
} else if (document.getElementById) {
// Modern browsers that support getElementById
}
Copy the code
The problem is that many modern browsers also implement document.all, which makes the code fall into old browser logic in all browsers.
From June to October 2009, there were 56 W3C mailing lists for Document. all.
The final result of the discussion is: in modern browsers, converting document.all to Boolean yields false.
In this way, the above code does not enter the old browser logic in modern browsers.
conclusion
In addition to the above features, Document. all also has some characteristics different from ordinary people, such as:
-
When being treated as == and! The = operator’s comparison object is treated as undefined
-
typeof document.all === 'undefined'
These quirky results are all for browser backwards compatibility. Although many modern browsers support document.all, it has been removed from the standard.
The only role I can think of for him at the moment is probably to argue with the interviewer……
Welcome to join the Human high quality front-end framework research group, Band fly