.outerHTML中不存在名称空间属性 [英] namespace attributes not present in .outerHTML

查看:101
本文介绍了.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 .getAttribute works:

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

当我使用.outerHTML并需要结果中包含名称空间信息时,这是一个潜在的问题.对于以编程方式创建的节点,名称空间信息可能会丢失,因此我可能不得不手动添加它.而这似乎是我不必在意"的事情-因此就是问题.

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.

您需要其中包含名称空间信息的.outerHTML的示例(请参阅

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

我要做的是

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

SVG->没有这个技巧,图像转换(如我所实现的)是行不通的.另请参阅我对上面链接的问题的回答.

SVG -> Image conversion (as I implemented it) doesn't work without this trick; see also my answer to the question linked above.

是否有更好/更优雅的方法来做到这一点? svgElt.getAttribute('xmlns')返回null的目的是什么?缺陷或特征?

Is there a better / more elegant way to do this? What is the objective of svgElt.getAttribute('xmlns') returning null? Flaw or feature?

推荐答案

您可以简单地使用 XMLSerializer ,它将把您的DOM树字符串化为xml,从而保留名称空间.

You can simply use an XMLSerializer for this, which will stringify your DOM tree to xml and thus preserve the namespaces.

const svgElt = document.createElementNS("http://www.w3.org/2000/svg", 'svg')
const serialized = new XMLSerializer().serializeToString(svgElt);
console.log(serialized);

这篇关于.outerHTML中不存在名称空间属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆