SVG Manipulation using JQuery

This started out as a simple idea. I have an Scalable Vector Graphics (SVG) image of the United States. I have data for several of those states. I want the state to be colored for the data, and to show the data in a Bootstrap popover on hover.

After doing a limited amount of research, one thing was clear, I needed to make sure I had the IDs set on my image correctly, and to do that I had two options. One was to edit the svg in a text editor – which would be fine except that I don’t know which path is Kentucky and which path is Oregon. So this could have created some serious confusion when you hover over California and see a popover for Maryland. Option two, was to use an SVG editor, and for me that is Inkscape. To do this in Inkscape, you simply select an element and press CTRL + SHIFT + O. This will bring up the object properties dialog (also accessible via the Object menu), and here you can provide an ID and a label for the shape. I had to do this for every shape with which I wished to interact. So, there were 50 total.

Attempt #1: (Note, this one was only a partial success – hence, the #1):

I pulled in the SVG as an object. Then using JQuery I was able to load the contents of the object. From there I was able to use selectors to access the id’s I added, and I could change the colors of the items – however I couldn’t get the popovers to fire. I tried several different approaches, and each one failed. My theory is that while I can traverse the SVG document object model to update fill styles, I can not tie it back to my HTML DOM in a meaningful way.

Arriving at this conclusion, I decided to paste that beast of SVG code into my HTML markup, which leads me to Attempt #2.

Attempt #2: (Success, but not my final solution)

So, now my HTML is huge, because it contains a massive amount of SVG data, but all of the elements and their id’s are part of the same DOM as my HTML markup now. Using the following HTML + JQuery I am able to access the document and do pretty much whatever I want with it.

First, the HTML

And the Script


Attempt #2.1 (My final solution)

So, for the final solution I wanted to get that nasty SVG code out of the markup. Because I realize that, while it doesn’t ease any bandwidth burden, it’s still more readable if you are viewing the HTML source. The only change there is to add a div, with a custom (in my case data-svg) attribute that points to your SVG file, then with JQuery you do the following


I created a similar project, specifically to share here, and it can be found on GitHub. I will try to post a demo and update this post in the near future.

Leave a Reply

Your email address will not be published. Required fields are marked *