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?
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:
console.log(document.createElement("svg") instanceof SVGElement)) // => false