javascriptsvg

How do I get all the attributes of an SVG path


I am trying to get attribute values of an SVG <path> element. I have the SVG file data as a string. I am currently using code similar to this to load the SVG data as an XML document which I can then query:

const parser = new DOMParser();
const doc = parser.parseFromString(data, "application/xml");
const elements = doc.getElementsByTagName("path");

Now I can use the attributes collection on the element to get the list of attributes. This works for some SVG files, but for others, some of the attributes are inherited, either from the <g> element, from the <svg> element, or maybe defined as a CSS style.

Is it possible to get all the attribute values including those that are inherited?


Solution

  • DOMParser does not apply CSS styles or inheritance logic—it parses the XML statically. So inherited styles or properties via <g> or <style> won't be available directly via getAttribute() or .attributes.

    If you can work in a browser context (not just parsing XML in memory), then: Inject the SVG string into the DOM (e.g., into a hidden <div>). Query the <path> element using querySelector(). Use getComputedStyle() to get inherited or computed style values.