admin管理员组文章数量:1375833
What is the difference between calling setAttribute and setAttributeNS with null as the namespace parameter?
Also is there an issue with using getAttribute() and then setAttributeNS ?
What is the difference between calling setAttribute and setAttributeNS with null as the namespace parameter?
Also is there an issue with using getAttribute() and then setAttributeNS ?
Share Improve this question asked Jan 28, 2016 at 9:46 SPlattenSPlatten 5,74813 gold badges72 silver badges137 bronze badges4 Answers
Reset to default 16setAttribute() is a DOM 1 function. setAttributeNS() is a DOM 2 function that resolves the problem of conflicting tag or attribute names by specifying the xmlns namespace that should apply to the tag/attribute in the first argument.
If an attribute does not have a defined namespace prefix, the first argument must be null. You could use setAttribute() but for consistency it is advisable to stick to setAttributeNS(). See:
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."
The setAttributeNS method is an XML method, and will not work with HTML elements.
Here's an explanation in English, from the MDN docs:
// 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:
// <div id="div1" width="200px" />
So from this, it appears that xmlns:special="http://www.mozilla.org/ns/specialspace"
is a declaration of the namespace special
, which is then used to contextualize special:specialAlign
.
setAttributeNS
is used for specifying the namespace and adds a new attribute with a namespace. NS
represent that. Also it requires three parameters
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.
本文标签: javascriptDifference between setAttribute and setAttributeNS(null Stack Overflow
版权声明:本文标题:javascript - Difference between setAttribute and setAttributeNS(null, - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738115901a2064699.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论