Accessing a div using id without getElementById and jQuery
我相信在 JS 中访问具有 id 的元素的标准方法是使用 getElementById。如果人们喜欢使用 jQuery,那么他们可能会使用他们的选择器。但最近我遇到了一个非常简单的代码示例,如下所示:
HTML:
1 | Hello |
JS:
1 | h.innerHTML ="Too bad"; |
这是唯一的代码,没有其他变量声明,仅供大家了解。
我们如何能够访问 div 元素,就好像它是一个 Javascript 对象一样?
附言:代码示例有效。
How are we able to access the div element as if it is a Javascript
object?
如果你这样做
的全局变量
根据规范,
Otherwise return an HTMLCollection rooted at the Document node, whose
filter matches only named objects with the name name. (By definition,
these will all be elements.)HTML elements that have an id content attribute whose value is name.
所以
参考 JavaScript 权威指南:
If you name an element in your HTML document using the id attribute, and if the
Window object does not already have a property by that name, the Window object is
given a nonenumerable property whose name is the value of theid attribute and whose name is the HTMLElement object that represents that document element.Window object serves as the global object at the top of the scope chain in client-side JavaScript, so this means that the id attributes you use in your HTML documents become global variables accessible to your scripts. If your document includes the element
, you can refer to that element using the global variable okay .
但也有一些例外。如果
其次,如果您有一个可用作窗口属性的 id,并且我们也声明了一个具有相同名称的变量,那么我们显式创建的变量将覆盖包含 id 的窗口属性。
为了实际演示上述答案...
HTML:
1 | <p>bar</p> |
Javascript:
1 2 | alert(window.foo); console.log(window.foo.innerHTML); |
警报:
1 | [object HTMLDivElement] |
控制台:
1 | <p>bar</p> |