使用没有getElementById和jQuery的id访问div [英] Accessing a div using id without getElementById and jQuery
问题描述
我相信JS中使用getElementById访问元素的标准方式是使用getElementById。如果人们喜欢使用jQuery,那么他们可能会使用他们的选择器。但最近我遇到了一个非常简单的代码示例,如下所示:
HTML:
< div id =h> Hello< / div>
JS:
h.innerHTML =太糟糕了;
这是唯一的代码,没有其他变量声明,仅供人们知道。 >
如何访问div元素,就好像它是一个Javascript对象?
PS :代码示例有效。
我们如何能够访问div元素是一个Javascript
对象?
$ / b
$ b $ p code是由创建的默认为全局对象的属性(在全局上下文中)。
如果您执行
< div id =h22 > Hello< / div>
它会创建一个全局变量h22
根据规范,
否则,返回以Document节点为根的HTMLCollection,其
过滤器仅匹配具有名称名称的命名对象。 (根据定义,
这些都是元素。)
具有名称为id content属性的HTML元素。
因此,
窗口
可以按照规范中给出的顺序确定从中选择价值。I believe that the standard way in JS to access an element with an id is by using getElementById. If people like to use jQuery, then they probably will use their selectors. But recently I came across a very simple code example which is below:
HTML:
<div id="h">Hello</div>
JS:
h.innerHTML = "Too bad";
This is the only code and there are no other variable declarations, just for people to know.
How are we able to access the div element as if it is a Javascript object?P.S. : The code example works.
解决方案How are we able to access the div element as if it is a Javascript object?
id
s are created by default as properties of global object (in global context).if you do
<div id="h22">Hello</div>
it will create a global variable ofh22
As per spec,
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.
So the
window
can determine in the order given in the spec where to pick the value from.这篇关于使用没有getElementById和jQuery的id访问div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!