.outerHTML中不存在名称空间属性 [英] namespace attributes not present in .outerHTML
问题描述
在HTML5/JavaScript中,如果我以编程方式创建命名空间的dom节点,如下所示:
In HTML5/JavaScript, if I create a namespaced dom node programmatically, like so:
svgElt = document.createElementNS("http://www.w3.org/2000/svg", 'svg')
节点知道"它是自己的名称空间,我可以像这样检索它:
the node 'knows' it's own namespace, which I can retrieve like so:
svgElt.namespaceURI // result: "http://www.w3.org/2000/svg"
但是命名空间不被视为普通"属性:
But the namespace is not treated as a "normal" attribute:
svgElt.getAttribute('xmlns') // result: null
因此,以编程方式创建的节点的行为不同于等效的直线"节点
So the behavior of the programmatically created node is different from the equivalent "straight" node
<svg xmlns="http://www.w3.org/2000/svg" id="mySVG"></svg>
: for which 当我使用 That is a potential problem when I use 您需要其中包含名称空间信息的 An example where you need 我要做的是 SVG->没有这个技巧,图像转换(如我所实现的)是行不通的.另请参阅我对上面链接的问题的回答. SVG -> Image conversion (as I implemented it) doesn't work without this trick; see also my answer to the question linked above. 是否有更好/更优雅的方法来做到这一点? Is there a better / more elegant way to do this? What is the objective of 您可以简单地使用 XMLSerializer ,它将把您的DOM树字符串化为xml,从而保留名称空间. You can simply use an XMLSerializer for this, which will stringify your DOM tree to xml and thus preserve the namespaces.
这篇关于.outerHTML中不存在名称空间属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!.getAttribute
works:document.getElementById('mySVG').getAttribute('xmlns') // result: "http://www.w3.org/2000/svg"
.outerHTML
并需要结果中包含名称空间信息时,这是一个潜在的问题.对于以编程方式创建的节点,名称空间信息可能会丢失,因此我可能不得不手动添加它.而这似乎是我不必在意"的事情-因此就是问题..outerHTML
and need namespace information contained in the result. The namespace info might be lost for the programmatically created nodes, and I might have to add it manually; and this seems like a thing "I shouldn't have to care about" - thus the question..outerHTML
的示例(请参阅.outerHTML
with namespace info in it is (see this question, Hubert OG 's answer) when you want to convert an inline SVG node into an Image
by setting the image source to a data url , as in'data:image/svg+xml,' + your_svg_element.outerHTML
svgNode.setAttribute('xmlns', svgNode.namespaceURI)
svgElt.getAttribute('xmlns')
返回null
的目的是什么?缺陷或特征?svgElt.getAttribute('xmlns')
returning null
? Flaw or feature?推荐答案
const svgElt = document.createElementNS("http://www.w3.org/2000/svg", 'svg')
const serialized = new XMLSerializer().serializeToString(svgElt);
console.log(serialized);