2013-12-23 89 views
26

我正在編寫一段基礎結構,需要對HTML元素與SVG元素進行不同的應用。給定一個DOM節點,如何判斷它是SVG還是HTML元素?如何判斷DOM元素是HTML還是SVG?

+3

不同意,這需要一個代碼示例來說明問題,這個問題是從文字清晰。 – David

+2

@大衛不僅是荒謬的緊密原因,但你會看到,問題得到了一個堅實的答案,可以在30分鐘內用於其他人。我不知道這些人在這裏想什麼。 –

回答

30

您可以嘗試類似以下內容:

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>

注意,<svg>元素本身實際上是一個HTML元素含有SVG元素 - 這意味着,也許令人驚訝的是,<svg> HTML元素一個SVG元素,因此:

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

這感覺更加直接。 –

+0

謝謝@BillCriswell,我想是的! –

+1

我做了if(element.getBBox){來檢查元素是否有getBBox方法。某些功能/方法僅適用於SVG元素。 –

1

我不知道如何跨瀏覽器兼容,但我戳穿DOM屬性,看到一個ownerSVGElement這似乎很有前途?

這裏去了我的玩弄與周圍:http://jsbin.com/uMIronal/4/edit?html,js,output

+2

請注意,除非已將SVG元素添加到文檔中,否則此方法不起作用 - 例如,document.createElementNS(「http://www.w3.org/2000/svg」,「circle」)。 ownerSVGElement'將是'null',所以'instanceof'更可靠,並且[性能更好](https://jsperf.com/check-if-svg-element/1)。 –

相關問題