When you use inline <svg>, all the elements are in the DOM, just like <div>s and <span>s and any other HTML element.

If you have SVG like:

  <rect id="foo" x="10" y="10" width="100" height="100" />

and you do:

var rect = document.getElementById("foo");

you'll get a reference to that <rect>.

And not only that, you can attach event listeners that work just as you'd expect. And you can adjust attributes and anything else you'd expect to be able to do with JavaScript.

There is at least one gotcha though, that has got me. We often attach event listeners to links, progressive enhancement style. In non-trivial JavaScript architecture, it's likely those event listeners pass the event around to other functions that handle the functionality. Relying on the this keyword in those situations gets tricky and often isn't recommended. Instead, since you have the event, you can use event.target. This can be just as tricky though, since with inline SVG the target could be the link, the SVG element itself, or any of the SVG shapes at all.

The solution is to traverse back up the DOM to an expected place. Or try and avoid the situation at all with:

svg {
  pointer-events: none;

Which I'd recommend if you don't plan on using any interactivity within the SVG themselves.


  1. User Avatar
    David Cummings
    Permalink to comment#

    If you uncheck “Responsive” in the SVG options, it will fix that annoying Illustrator viewbox problem.

Leave a Comment

Posting Code!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.