Javascript:setAttribute() 与 setAttribute() 比较element.attribute = 设置 "name"属性的值

标签 javascript setattribute getelementsbyname

所以我正在学习操作 DOM,并且我注意到一件有趣的事情:

假设我想使用“.”设置元素的 name 属性。点符号:

element.name = "someName";
console.log(document.getElementsByName("someName")[0]); // returns "undefined"??

但是,如果我使用 document.setAttribute() 方法,它就可以正常工作:

element.setAttribute("name", "someName");
console.log(document.getElementsByName("someName")[0]); // returns the element like it should.

不确定为什么点表示法在第一种情况下不起作用。

为什么会发生这种情况?

最佳答案

我的猜测(因为您没有指定元素类型)是该元素通常没有 name 属性,因此这样设置 DOM 属性是行不通的。

例如,在 input 元素上设置 name 属性即可。将其设置在 div 上不会。

但是,它可以与 setAttribute() 一起使用。

jsFiddle .

关于Javascript:setAttribute() 与 setAttribute() 比较element.attribute = 设置 "name"属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43723359/

相关文章:

javascript - JSON 序列化在 loadFromJSON 之后忽略 fabric.js 中的自定义属性

javascript - MVC 应用程序不在 View 中显示数据

javascript - node.setAttribute ('attName' ,null) 返回类型不匹配

javascript - 在javascript中使用循环动态检索元素

javascript - 为什么 GetElementsByTagName 不能以这种形式工作?

javascript - 如何使用 c3.js 将 json 数据集设置为图表的标签

javascript - 从静态方法中创建实例

plot - Julia 绘图 : delete and modify existing lines

javascript - IE7 的 onclick setAttribute 解决方法

javascript - 如何使用javascript检查标签是否存在而不会出错