例子

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="testId" class="testClass">凯小默测试页面</div>
<script>.log('1111', testId);
console.log('2222', testClass);</script>
</body>
</html>

结果

id能直接打印出来dom,class的不行(谷歌浏览器打开)

为什么dom元素可以直接使用id名称来获取元素?_js

谷歌

为什么dom元素可以直接使用id名称来获取元素?_js_02

firefox

为什么dom元素可以直接使用id名称来获取元素?_html_03

ie7-ie8

为什么dom元素可以直接使用id名称来获取元素?_js_04

ie9-ie11

为什么dom元素可以直接使用id名称来获取元素?_原型链_05

原因

如果dom元素的id名称不和js内置对象属性或全局变量重名的话,该名称能从window原型链上进行查找的属性,Firefox、Chrome、IE 9-11都支持,没有形成标准,而且容易污染全局,造成各种冲突和错误,不推荐使用。

我们看一个有趣的东西

​https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor​

​Object.getOwnPropertyDescriptor()​

方法返回指定对象上一个自有属性对应的属性描述符。(自有属性指的是直接赋予该对象的属性,不需要从原型链上进行查找的属性)

1、testId显然不是window自有属性对应

Object.getOwnPropertyDescriptor(window, 'testId')  // --->  undefined

2、在原型链上,​​window.__proto__.__proto__​​上面找到了testId

Object.getOwnPropertyDescriptor(window.__proto__.__proto__, 'testId')

为什么dom元素可以直接使用id名称来获取元素?_js_06