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?
The easiest way to find an HTML element in the DOM, is by using the element id.
if(typeof obj. innerHTML!==
SVG is a language for describing 2D graphics in XML. Canvas draws 2D graphics, on the fly (with a JavaScript). SVG is XML based, which means that every element is available within the SVG DOM.
Document object model. The DOM is the way Javascript sees its containing pages' data. It is an object that includes how the HTML/XHTML/XML is formatted, as well as the browser state. A DOM element is something like a DIV, HTML, BODY element on a page.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With