Javascript:setAttribute()v.s. element.attribute =要设置“名称”的值属性 [英] Javascript: setAttribute() v.s. element.attribute = value to set "name" attribute
问题描述
所以我正在学习操纵DOM,我注意到一件有趣的事情:
So I'm learning to manipulate the DOM and I noticed one interesting thing:
假设我要设置名称
使用。元素的属性。点表示法:
Let's say I want to set the name
attribute of an element by using the "." dot notation:
element.name = "someName";
console.log(document.getElementsByName("someName")[0]); // returns "undefined"??
但是,如果我使用 document.setAttribute()
方法,它工作正常:
However if I use the document.setAttribute()
method, it works fine:
element.setAttribute("name", "someName");
console.log(document.getElementsByName("someName")[0]); // returns the element like it should.
不确定为什么点符号方法在第一种情况下不起作用。
Not sure why the dot notation method doesn't work in the first case.
为什么会这样?
推荐答案
我的猜测(因为你没有指定元素类型)元素通常没有 name
属性,所以设置这样的DOM属性是行不通的。
My guess (because you didn't specify the element type) is the element normally does not have a name
attribute, so setting the DOM property like that won't work.
例如,在输入
元素上设置 name
属性将起作用。在 div
上设置它不会。
For example, setting the name
property on an input
element will work. Setting it on a div
will not.
然而,它将起作用 setAttribute ()
。
jsFiddle 。
这篇关于Javascript:setAttribute()v.s. element.attribute =要设置“名称”的值属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!