Skip to main content Accessibility Feedback

Detecting SVG support with JavaScript

Modernizr is a very popular browser support detection generator, but sometimes it can be a little heavy-handed when you just need to check one or two things.

Take SVG support, for example. You can reliably test SVG support with one line of code:

var svgSupport = !!document.createElementNS && !!document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect;

You can then do things like add a conditional class to your webpage only if SVG is supported:

var svgSupport = !!document.createElementNS && !!document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect;
if ( svgSupport ) {
    document.documentElement.className += ' svg';
}

Then, you can hook into that class in your CSS for conditional styling.

svg {
    /* Default styles */
}

.svg svg {
    /* Styles when SVG is supported */
}

🚀 Make 2018 the year you master JavaScript! My pocket guides and mini courses are short, focused, and made for beginners. You can do this!

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips