Javascript:setAttribute()v.s.element.attribute=要设置的值;名称“;属性

Javascript:setAttribute()v.s.element.attribute=要设置的值;名称“;属性,javascript,setattribute,getelementsbyname,Javascript,Setattribute,Getelementsbyname,所以我正在学习操作DOM,我注意到一件有趣的事情: 假设我想使用“.”点符号设置元素的name属性: element.name = "someName"; console.log(document.getElementsByName("someName")[0]); // returns "undefined"?? 但是,如果我使用document.setAttribute()方法,它可以正常工作: element.setAttribute("name", "someName"); conso

所以我正在学习操作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属性是行不通的

例如,在
输入
元素上设置
名称
属性将起作用。将其设置为
div
将不起作用

但是,它将与
setAttribute()
一起工作


.

使用element.name时,您正在访问属性/创建名为“name”的属性并设置其值

但是,

在使用element.setAttribute('name','someName')时,实际上是在设置属性'name'

IE8及以下版本将属性和属性视为相同,该错误已在IE9及以上版本中修复。
Safari、FireFox、Chrome以不同的方式处理属性和属性


但是,如果愿意,您可以随时创建自己选择的新属性。

要扩展其他一些属性提供的答案

属性“name”仅被认为是少数特定对象的有效DOM。根据这些目标:

 <a>, <applet>, <button>, <form>, <frame>, <iframe>, <img>, <input>, 
 <map>, <meta>, <object>, <param>, <select>, and <textarea>
为例。顺便说一句-加载时的警报框是故意的-检查代码以了解原因…


<head>
<script>
function test($count) {
document.getElementById("test1").setAttribute("name","file-upload_" + $count);
}
</script>
</head>
<body>

<p>some content</p>
<input id="test1" type="file" name="file-upload" id="file-upload" />
<p>some other content</p>
<script>test(1);</script>
</body>
功能测试($count){ document.getElementById(“test1”).setAttribute(“名称”、“文件上传”+$count); } 一些内容

其他一些内容

试验(1);
(试图单独更好地解释上述帖子的一部分,因为它已经进入-ve评级,对该帖子的信任度会降低。如果不是更好的话,请帮助进一步改进。)

***
属性

使用element.name时,您正在访问名为“name”的现有
属性或设置其值

Example 1:
var div1 = document.getElementById("div1"); 
div1.textContent = "2";
***
属性

但是,在使用
element.setAttribute('name','someName')
时,实际上是在设置名为'name'的
属性。
此属性可以是现有属性,也可以是我们想要的自定义属性:

Example 2:
var h1 = document.getElementById("H1"); 
h1.setAttribute("class", "democlass");

Example 3:
var d = document.getElementById("d1"); 
d.setAttribute("name1", "value1");

使用element.name时,您正在访问属性/创建名为“name”的属性并设置其值。

通常尝试避免使用
getElementsByName
为什么要避免使用getElementsByName?如果您希望访问属性,可以使用点符号访问属性。如果希望使用点表示法访问属性,则需要参考obj.attributes.attributeName来检索属性,并参考obj.attributeName.value来操作其值。与setAttribute或getAttribute相比,它是冗长的。不建议将其作为解决方案,但不管怎样,对您的问题“为什么点符号在第一种情况下不起作用”的完整答案必须包括“它起作用。您只是在错误的位置查找属性及其值。”部分答案。。。当我将某个html元素属性设置为“undefined”时,它不起作用,并且继续使用它以前的值。你能告诉我为什么会这样吗?@SurajJain可能是因为API不允许属性
未定义。