Without a Doctype, querySelector('#main') Finds Elements getElementById('main') Can't
You're adding a script to an old page, or a page someone else wrote, with this markup:
<html>
<body>
<div id="Main" class="Intro">…</div>
</body>
</html>
Your code gets the case wrong, but only some of it fails:
document.querySelector('#main'); // <div id="Main">
document.querySelectorAll('.intro'); // NodeList [div#Main]
document.getElementById('main'); // null
div.classList.contains('intro'); // false
document.querySelectorAll('[id="main"]'); // NodeList []
Add <!doctype html> to the top of the same page and the first two
lines return null and an empty list too.
Short answer: a page without a doctype is rendered in
quirks mode, and in quirks mode ID selectors (#main) and class
selectors (.intro) compare names without regard to case. Nothing else
does: getElementById(), classList and attribute selectors
stay case-sensitive. Add <!doctype html> if you can. If you can't,
use attribute selectors when you need an exact match:
document.querySelectorAll('[id="Main"]'); // only id="Main"
document.querySelectorAll('[class~="Intro"]'); // only class "Intro"
Why quirks mode changes #id and .class
Browsers render pages without a doctype in quirks mode, which copies the behaviour of
browsers from the late 1990s so that old pages keep working. One of those old
behaviours is that CSS like .Intro { … } applied to
class="intro".
The HTML spec keeps it, in its section on
case-sensitivity of selectors:
ID and class selectors matched against elements in a quirks-mode document are
compared case-insensitively (for ASCII letters). querySelectorAll() uses
the same selector engine as CSS, so it inherits the rule. getElementById()
isn't a selector; it's defined in the DOM spec as an exact comparison, and quirks mode
doesn't touch it.
It has tripped up the people who implement selectors, not just page authors: see
W3C bug 23781,
jsdom #1877,
a Jint issue about
getElementsByClassName(), a
WordPress HTML API ticket
and a dommy pull request
that had to make getElementById() case-sensitive again after its
selector engine got quirks mode right.
What ignores case and what doesn't
I tested each of these in Chromium 159 and Firefox 159 on a no-doctype page containing
<p id="Main" class="Intro"> and <p id="main">.
Both browsers gave the same results:
Call Quirks mode Standards mode
querySelectorAll('.intro') 1 match 0
querySelectorAll('.INTRO') 1 match 0
querySelectorAll('#MAIN') 2 matches 0
element.matches('.INTRO') true false
CSS rule .intro { … } applies doesn't apply
getElementsByClassName('intro') 1 match 0
getElementById('MAIN') null null
classList.contains('intro') false false
querySelectorAll('[class~="intro"]') 0 0
querySelectorAll('[id="MAIN"]') 0 0
getElementsByClassName() is the odd one out among the DOM methods: the
DOM spec makes it follow quirks mode too, so it agrees with .intro.
getElementById() and classList don't.
Which documents are in quirks mode
Check any document with document.compatMode. It's
"BackCompat" in quirks mode and "CSS1Compat" otherwise.
These were the results in both browsers:
Document compatMode .intro matches "Intro"
page with no doctype BackCompat yes
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
(no system identifier) BackCompat yes
the same doctype with "http://www.w3.org/TR/html4/loose.dtd"
CSS1Compat no
XHTML 1.0 Transitional doctype CSS1Compat no
<!doctype html> CSS1Compat no
new DOMParser().parseFromString(html, 'text/html'),
html without a doctype BackCompat yes
<iframe> with no src (about:blank) BackCompat yes
<iframe srcdoc="…"> CSS1Compat no
document.implementation.createHTMLDocument() CSS1Compat no
template.content in a quirks-mode page CSS1Compat no
The two old doctypes that report CSS1Compat are in limited
quirks mode, which changes some layout rules but keeps selectors
case-sensitive.
The pages you'll meet in quirks mode are mostly old sites, generated reports, HTML emails and intranet tools. That matters most when your code runs on pages you don't control: a browser extension, a bookmarklet, a userscript, or a scraper.
Gotcha: DOMParser makes quirks-mode documents
Your own page can have a doctype and still hit this. When you parse an HTML snippet
with DOMParser, the snippet usually has no doctype, so the new document
is in quirks mode:
const doc = new DOMParser().parseFromString('<p class="Intro">Hi</p>', 'text/html');
doc.compatMode; // "BackCompat"
doc.querySelectorAll('.intro'); // NodeList [p.Intro]
const strict = new DOMParser().parseFromString('<!doctype html><p class="Intro">Hi</p>', 'text/html');
strict.querySelectorAll('.intro'); // NodeList []
So the same selector gives different results on the parsed document and on your page.
If you parse snippets and query them, prepend <!doctype html> to
the string, or use a <template> element, whose content follows
standards-mode rules.
Gotcha: #main can match two different IDs
IDs that differ only by case are different IDs. In quirks mode, an ID selector matches all of them:
<p id="Main">…</p>
<p id="main">…</p>
document.querySelectorAll('#main'); // NodeList(2) [p#Main, p#main]
document.querySelector('#main'); // <p id="Main">, the first in the document
document.getElementById('main'); // <p id="main">
querySelector('#main') and getElementById('main') return
different elements here. Code that mixes the two can end up reading one element and
writing to another.
Getting exact matches in quirks mode
The best fix is a doctype. Adding <!doctype html> to an old page
can change its layout, though, so check the page afterwards. If you can't change the
page, use attribute selectors. The HTML spec lists only a few attributes, such as
type, dir and lang, whose values are compared
without regard to case; id and class aren't among them, so
attribute selectors match them exactly in every mode:
// Exact ID
document.querySelectorAll('[id="Main"]');
// Exact class: ~= matches one word in the space-separated list, like .Intro
document.querySelectorAll('[class~="Intro"]');
// Combine with anything else
document.querySelectorAll('ul[class~="Nav"] > li[class~="Active"]');
It works the other way too. If you want case-insensitive matching on every page, not
only quirks-mode ones, add the i flag:
[class~="intro" i] matches class="Intro" in any mode.
Try it in your browser
This page has a doctype, so the demo parses the same markup twice with
DOMParser: once without a doctype and once with one.
Results will appear here.
Summary
-
A page without a doctype is in quirks mode, where
#idand.classselectors ignore case, inquerySelectorAll(),matches()and CSS alike. -
getElementById(),classListand attribute selectors stay case-sensitive, so they can disagree withquerySelector().getElementsByClassName()follows quirks mode like.classdoes. -
Check with
document.compatMode === 'BackCompat'. Besides no-doctype pages,DOMParseroutput without a doctype andabout:blankiframes are in quirks mode. -
In quirks mode,
#mainmatchesid="Main"andid="main"at once. -
Add
<!doctype html>, or use[id="…"]and[class~="…"]for exact matches.