“Read” — JSCourse, dedicated to the selection of high-quality JavaScript related technical content
Recently xiaobian saw a foreign engineer wrote an article, xiaobian feel or very interesting. What is it? In a nutshell, he found that
Any DOM element in HTML with an ID is directly accessible through the Window object
If you already know this, then you don’t need to read on. If you are like xiaobian, you may want to read on for more details.
When you write a DOM element with an ID in your HTML code, it looks like this:
<div id="jscourse"></div>
Copy the code
So in general, to get this DOM element, you do:
document.getElementById('jscourse');
Copy the code
or
document.querySelector('#jscourse');
Copy the code
But, interestingly, you can also do this directly:
Jscourse // or directly jscourseCopy the code
What the hell! Does this mean that the browser exposes the DOM element containing the ID to the window object?
Xiaobian to find the next W3C standard, yo, there really is this:
It also indicates that if two or more DOM elements containing the same ID are encountered, an array containing all of them is returned. However, it is worth noting that not all browsers are implemented according to standards.
Isn’t that interesting? You can try it yourself.
So what’s the value of this? You should use the BROWSER API to retrieve DOM elements, but you can use this method for debugging (although you should avoid using IDS for HTML). Also, once you learn about it, you’ll be able to wonder if it’s the cause of a strange bug later on.
Well, this is just to give you an idea of how to use it. See you next time!
Follow jscourse on wechat for more courses and materials.