如何判断DOM元素是HTML还是SVG?

时间:2022-08-27 00:10:09

I am writing a piece of infrastructure that needs to be applied differently to HTML elements versus SVG elements. Given a DOM node, how can I tell if it''s an SVG or HTML element?

我正在编写一段基础设施,需要对HTML元素和SVG元素进行不同的应用。对于DOM节点,如何判断它是SVG还是HTML元素?

2 个解决方案

#1


31  

You may try something like the following:

你可以试试以下方法:

if(document.getElementById("el") instanceof SVGElement) {
    console.log("It's an SVG element");
}
<svg xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink" 
  width="300" height="300">
  <g id="firstGroup">
    <rect id="el" width="100" height="50" x="40" y="20" fill="blue" />
    <text x="40" y="100">This is a basic SVG document!</text>
  </g>
</svg>

Note that the <svg> element itself is actually an HTML element containing SVG elements - which means that, perhaps surprisingly, the <svg> HTML element is not an SVG element, hence:

注意, 元素本身实际上是一个包含svg元素的HTML元素——这意味着,也许令人惊讶的是, HTML元素不是svg元素,因此:

console.log(document.createElement("svg") instanceof SVGElement)) // => false

#2


1  

I'm not sure how cross browser compatible it is but I was poking through the DOM properties and saw a ownerSVGElement which seems promising?

我不确定跨浏览器是否兼容,但我在DOM属性中查找了一个ownerSVGElement,它看起来很有前途?

Here goes what I was toying around with: http://jsbin.com/uMIronal/4/edit?html,js,output

下面是我要讨论的内容:http://jsbin.com/uMIronal/4/edit?html,js,输出。

#1


31  

You may try something like the following:

你可以试试以下方法:

if(document.getElementById("el") instanceof SVGElement) {
    console.log("It's an SVG element");
}
<svg xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink" 
  width="300" height="300">
  <g id="firstGroup">
    <rect id="el" width="100" height="50" x="40" y="20" fill="blue" />
    <text x="40" y="100">This is a basic SVG document!</text>
  </g>
</svg>

Note that the <svg> element itself is actually an HTML element containing SVG elements - which means that, perhaps surprisingly, the <svg> HTML element is not an SVG element, hence:

注意, 元素本身实际上是一个包含svg元素的HTML元素——这意味着,也许令人惊讶的是, HTML元素不是svg元素,因此:

console.log(document.createElement("svg") instanceof SVGElement)) // => false

#2


1  

I'm not sure how cross browser compatible it is but I was poking through the DOM properties and saw a ownerSVGElement which seems promising?

我不确定跨浏览器是否兼容,但我在DOM属性中查找了一个ownerSVGElement,它看起来很有前途?

Here goes what I was toying around with: http://jsbin.com/uMIronal/4/edit?html,js,output

下面是我要讨论的内容:http://jsbin.com/uMIronal/4/edit?html,js,输出。