Why querySelectorAll('lineargradient') Works in Chrome but Not in Firefox
You have an inline SVG with a gradient, and you want to find it:
<svg>
<defs>
<linearGradient id="fade"></linearGradient>
</defs>
</svg>
document.querySelectorAll('lineargradient');
// Chrome: NodeList [linearGradient#fade]
// Firefox: NodeList []
It works in Chrome, so you ship it, and then it silently finds nothing in Firefox.
Short answer: SVG tag names are case-sensitive. Write them exactly as the SVG spec spells them, with the capital letters:
document.querySelectorAll('linearGradient'); // works in every browser
document.querySelectorAll('clipPath');
document.querySelectorAll('foreignObject');
The rule: HTML tag names ignore case, SVG tag names don't
You've probably written querySelectorAll('DIV') or
querySelectorAll('Div') at some point and had it work. In an HTML
document, type selectors match HTML elements regardless of case, so div,
DIV and Div all mean the same thing.
That rule only covers elements in the HTML namespace. An <svg>
element and everything inside it are in the SVG namespace, and SVG comes from XML,
where names are case-sensitive. The HTML spec only makes type selectors
case-insensitive for HTML elements, so for SVG elements the selector has to match the
element's name exactly.
The parser already does the work of getting the name right. Even if your markup says
<lineargradient>, the HTML parser fixes the case when it creates
the element inside an <svg>:
const gradient = document.querySelector('svg').firstElementChild;
gradient.localName; // "linearGradient"
gradient.tagName; // "linearGradient"
gradient.namespaceURI; // "http://www.w3.org/2000/svg"
So the element is always called linearGradient, and
'linearGradient' is the selector that matches it.
Why it works in Chrome but not in Firefox
Browsers don't agree on this. I ran the same selectors in Chromium 159 and Firefox 159 against an inline SVG in an HTML page:
Selector Chromium 159 Firefox 159
'linearGradient' matches matches
'lineargradient' matches no match
'LINEARGRADIENT' matches no match
'clippath' matches no match
'foreignobject' matches no match
'SVG' matches no match
'DIV' matches matches
getElementsByTagName('lineargradient') 0 found 0 found
Firefox follows the rule above: case only stops mattering for HTML elements, so
'DIV' works but 'SVG' and 'lineargradient'
don't. Chromium ignores case for SVG elements too.
That's what makes this bug easy to ship. If you develop in Chrome, a lowercase
selector works every time you test it. Notice that
getElementsByTagName() is case-sensitive for SVG elements in both
browsers, so it's only selectors that behave differently.
I couldn't test Safari for this article. Use the demo below to see what your browser does. Either way, the exact spelling works everywhere, so that's what to write.
Which SVG elements are affected
Only SVG elements whose names contain a capital letter. svg,
path, g, rect, circle,
use, text and the other all-lowercase names are already
written the way they're defined, so a lowercase selector matches them in every
browser. (Uppercase ones like 'SVG' or 'PATH' fail in
Firefox, though.)
These are the ones to watch:
linearGradient radialGradient clipPath foreignObject
textPath animateMotion animateTransform
feBlend feColorMatrix feComponentTransfer
feComposite feConvolveMatrix feDiffuseLighting
feDisplacementMap feDistantLight feDropShadow
feFlood feFuncA feFuncB
feFuncG feFuncR feGaussianBlur
feImage feMerge feMergeNode
feMorphology feOffset fePointLight
feSpecularLighting feSpotLight feTile
feTurbulence
Gradients, clip paths, foreignObject and the filter primitives
(fe…) are where people usually run into it.
Gotcha: code that lowercases your selector
Sometimes you did write linearGradient, but something between you and
querySelectorAll() lowercased it. Look out for:
-
Building selectors from
tagNameornodeNameand then normalizing them. Code likeel.tagName.toLowerCase()is a common habit from HTML, wheretagNamecomes back uppercase ("DIV"). For SVG elementstagNameis already correct ("linearGradient"), and lowercasing it breaks it. Useel.localName, which gives the right name for both HTML and SVG elements without any changes. - Selector generators and testing tools that lowercase type selectors. For example, a jsdom regression made type selectors stop matching camelCase SVG elements because of a lowercasing comparison (domSelector issue #353).
- Selectors stored in places that change case, like configuration files, database columns or URL parameters that get normalized.
Gotcha: closest(), matches() and CSS have the same problem
Anything that takes a CSS selector follows the same rule, with the same browser difference. This one is easy to miss in event delegation:
document.addEventListener('click', (event) => {
const embed = event.target.closest('foreignobject'); // null in Firefox
// ...
});
// Results in Chromium 159 / Firefox 159
div.closest('foreignobject'); // found / null
div.closest('foreignObject'); // found / found
gradient.matches('lineargradient'); // true / false
Stylesheets work the same way:
lineargradient { /* applies in Chromium, ignored in Firefox */ }
linearGradient { /* applies in both */ }
Gotcha: creating the element with the wrong case
If you build SVG with JavaScript, the case matters there too, and getting it wrong creates an element the browser doesn't recognize:
const SVG_NS = 'http://www.w3.org/2000/svg';
document.createElementNS(SVG_NS, 'linearGradient'); // a real gradient
document.createElementNS(SVG_NS, 'lineargradient'); // an unknown SVG element; does nothing
document.createElement('linearGradient'); // an unknown HTML element named "lineargradient"
The broken versions don't render as gradients, and in Chromium a
'linearGradient' selector still matches the wrongly-cased
createElementNS() element, because Chromium ignores case. So your query
finds the element but it doesn't work. Check el.localName: it should be
exactly "linearGradient".
Unlike selectors, setting innerHTML is safe: the HTML parser fixes the
case for you, so svg.innerHTML = '<lineargradient></lineargradient>'
creates a real linearGradient.
Matching a tag name when you don't know its case
If the tag name comes from user input or another system and might be in any case, there's no case-insensitive type selector to use. Select more broadly and compare the names yourself:
function queryTagIgnoringCase(root, name) {
const wanted = name.toLowerCase();
return [...root.querySelectorAll('*')]
.filter((el) => el.localName.toLowerCase() === wanted);
}
queryTagIgnoringCase(document, 'LINEARGRADIENT'); // [linearGradient#fade]
If you know the elements are SVG, getElementsByTagNameNS() is another
option. It's also case-sensitive, but it lets you restrict the search to the SVG
namespace:
document.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'linearGradient');
Try it in your browser
This page contains a hidden SVG with a linearGradient, a
clipPath and a foreignObject containing a
<div>. Press the button to run the selectors from this article
against it and see what your browser returns:
<svg id="demo-svg">
<defs>
<linearGradient id="gradient"></linearGradient>
<clipPath id="clip"></clipPath>
</defs>
<foreignObject id="foreign">
<div id="inner"></div>
</foreignObject>
</svg>
Results will appear here.
Summary
- In an HTML document, type selectors ignore case for HTML elements, but not for SVG elements, which have to be matched by their exact name.
-
Chromium matches SVG tag names regardless of case and Firefox doesn't, so
querySelectorAll('lineargradient')works in Chrome and finds nothing in Firefox. -
Write SVG tag names exactly as defined:
linearGradient,clipPath,foreignObject,textPathand thefe…filter elements. All-lowercase names likepathare fine. -
The same applies to
closest(),matches()and stylesheets. -
Don't lowercase
tagNameto build selectors; useel.localName. Create SVG elements withcreateElementNS()and the exact name. -
To match a tag name in any case, filter on
el.localName.toLowerCase()yourself.