namespace attributes not present in .outerHTML

*爱你&永不变心* 提交于 2020-06-01 05:25:43

问题


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 .getAttribute works:

document.getElementById('mySVG').getAttribute('xmlns') // result: "http://www.w3.org/2000/svg"

That is a potential problem when I use .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.

An example where you need .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

What I do is

svgNode.setAttribute('xmlns', svgNode.namespaceURI)

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 svgElt.getAttribute('xmlns') returning null? Flaw or feature?

来源:https://stackoverflow.com/questions/62109331/namespace-attributes-not-present-in-outerhtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!