Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell if a DOM element is HTML or SVG?

Tags:

html

dom

svg

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?

like image 738
George Mauer Avatar asked Dec 23 '13 18:12

George Mauer


People also ask

How do I identify a DOM element?

The easiest way to find an HTML element in the DOM, is by using the element id.

How do you check if an object is an HTML element?

if(typeof obj. innerHTML!==

Is SVG a DOM element?

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.

What is the type of a DOM element?

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.


1 Answers

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 
like image 161
The Alpha Avatar answered Sep 22 '22 03:09

The Alpha