关于javascript:setAttribute和setAttributeNS(null,

Difference between setAttribute and setAttributeNS(null,

使用null作为命名空间参数调用setAttribute和setAttributeNS有什么区别?

使用getAttribute()然后再使用setAttributeNS还有一个问题吗?


setAttribute()是DOM 1函数。 setAttributeNS()是DOM 2函数,通过在第一个参数中指定应应用于标签/属性的xmlns命名空间来解决标签或属性名称冲突的问题。

如果没有定义属性名称空间前缀,第一个参数必须为null。您可以使用setAttribute(),但是为了保持一致性,建议坚持使用setAttributeNS()。请参阅:

https://developer.mozilla.org/en/docs/Web/SVG/Namespaces_Crash_Course#Scripting_in_namespaced_XML

"However, note carefully: the Namespaces in XML 1.1 recommendation
states that the namespace name for attributes without a prefix does
not have a value. In other words, although the attributes belong to
the namespace of the tag, you do not use the tag's namespace name.
Instead, you must use null as the namespace name for unqualified
(prefixless) attributes."


这是来自MDN文档的英语解释:

1
2
3
4
5
6
7
8
9
// Given:
//   <div id="div1" xmlns:special="http://www.mozilla.org/ns/specialspace"
//     special:specialAlign="utterleft" width="200px" />

d = document.getElementById("div1");
d.removeAttributeNS("http://www.mozilla.org/ns/specialspace","specialAlign");

// Now:
//

因此,由此看来,xmlns:special="http://www.mozilla.org/ns/specialspace"是名称空间special的声明,然后用于对special:specialAlign


setAttributeNS用于指定名称空间,并添加带有名称空间的新属性。 NS代表这一点。还需要三个参数

1
2
3
4
5
6
7
element.setAttributeNS(ns,name,value)

ns  :namespace URI of the attribute to set
name:Name of the attribute to set
value:Value of the attribute to set

setAttribute(name,value) which is use to add a new attribute or change the value of existing attribute.


setAttributeNS方法是XML方法,不适用于HTML元素。