javascript - javascript中通过ID访问元素

标签 javascript html

我无意中发现只需输入元素的 id 即可访问元素,例如:

<input id="test" value="testValue"/>
<script>
   console.log(test.value); //testValue
</script>

有人能指出我这个功能来自哪里吗? (用谷歌搜索这样的东西真的很难)

最佳答案

From the spec:

window[name]

Returns the indicated element or collection of elements.

As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use document.getElementById() or document.querySelector().

关于javascript - javascript中通过ID访问元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35708490/

相关文章:

javascript - webpack --env.production 和 --mode ="production"有什么区别

javascript - 使用 jquery 将 div 移动到其他 div 上

javascript - 动态更改 html5 输入控件的必需属性

java - 随着 HTML5 <canvas> 元素的引入,Swing 是否可以在 GWT 中实现?

javascript - 哪个图像有类,更改 src JQUERY

jquery - 使用 Bootstrap 使输入/表单栏响应

javascript - Summernote 在 POST 中添加 "files"字段

javascript - 在特定日期后上传的网站中的所有图像都拒绝加载

javascript - [React-Native]有没有办法像webpack一样设置路径别名?

javascript - AngularJS - 使用 ng-click 非顺序调用两个函数