Get id of clicked svg path with javascript
<p>I have an SVG map of counties in Massachusetts. The svg file contains paths outlining each county, and each path has the name of the county as its <code>id</code>. I need to grab the <code>id</code> of the county when it is clicked, so that it can be set to a variable.</p>

<p><strong>Edit:</strong> The SVG is an external file (it's a map with a ton of path coordinates; it seems like it would be messy to copy/paste the whole thing directly into the HTML, so it's being loaded from the external file). Here is a sample of the svg file:</p>

<pre><code>&lt;?xml version="1.0" encoding="iso-8859-1"?&gt;
&lt;?xml-stylesheet type="text/css" href="co25_d00.css"?&gt;
&lt;!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20000303 Stylable//EN"
    "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"&gt;

&lt;svg id="MACounties"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   version="1.0" width="100%" height="100%" preserveAspectRatio="xMidYMax" viewBox="12.711167 456.567074 29.566845 18.433033"&gt;
&lt;title&gt;Libre Map Project&lt;/title&gt;
&lt;g transform="scale(1.0,-1.0) translate(0,-931.567181)"&gt;
&lt;g id="Unknown_Area_Type_co25_d00_e00" style="fill:'currentColor';pointer-events:visible;stroke:rgb(1,0,0);stroke-width:0.01;stroke-linecap:round"&gt;
    &lt;path id="Essex" d="M34.363079 474.99995L34.363179 474.99967 34.363179 474.99967 34.462128 474.99704 34.596972 474.95046...&gt;
</code></pre>

<p><strong>Edit 2:</strong> This is the HTML file where the image is being loaded.</p>

<pre><code>&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Untitled&lt;/title&gt;
    &lt;link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"&gt;
    &lt;link rel="stylesheet" type="text/css" href="co25_d00.css"&gt;
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;
        $(function(){

              var container = $("#map");
              var svgUrl    = "co25_d00.svg";
              var xmlDoc;

              $.get(svgUrl)
                .then(injectSvg);

              function injectSvg(xmlDoc) {
                var svg = $(xmlDoc).find("svg");
                container.append(svg);
              };

              $(document).ready(function() {
                $('path').onclick = function() {
                    alert($(this).attr('id'));
                };
              });
            });
    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div id="map"&gt;&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>