querySelectorAll(':target') Returns the Old Element After history.pushState()
Your page was loaded at /docs#intro. Your router then moves to another
section with history.pushState():
history.pushState(null, '', '#install');
location.hash; // "#install"
document.querySelectorAll(':target'); // NodeList [p#intro] (not #install)
The address bar says #install, but :target still matches
#intro. Your :target CSS highlights the wrong section too.
Short answer: pushState() and
replaceState() change the URL without navigating, and only a navigation
changes which element is the target. Do a same-page navigation to the current URL,
then put your history state back:
function updateTarget() {
const state = history.state;
if (location.hash) {
location.replace(location.href); // navigate to the current #hash
} else {
location.replace('#'); // clear :target
}
history.replaceState(state, '', location.href.replace(/#$/, ''));
}
history.pushState(null, '', '#install');
updateTarget();
document.querySelectorAll(':target'); // NodeList [p#install]
Why pushState() doesn't change :target
:target doesn't read the URL each time it's checked. The document keeps
a separate record of its target element, and the HTML spec only updates that
record when the browser navigates to a fragment: clicking a #link,
setting location.hash, going back or forward, or loading the page.
pushState() and replaceState() are deliberately not
navigations. They rewrite the URL and the session history entry and nothing else: no
scrolling, no hashchange event, and no change to the target element.
Browsers have behaved this way for over a decade. Bug reports were filed against
Chromium,
WebKit and
Firefox, and the
HTML spec discussion settled
on keeping it, so don't expect it to change.
That's why it shows up in single-page apps: routers use pushState() for
every link, including same-page #hash links, so :target gets
stuck on whatever the page loaded with. (See
this Qwik issue for one
example.)
What updates :target and what doesn't
I tested each of these in Chromium 159 and Firefox 159, starting from a page loaded at
#a and then calling history.pushState(null, '', '#b'). Both
browsers gave the same results:
Action after pushState(..., '#b') :target is now
nothing #a
location.hash = '#b' #a
element.scrollIntoView() #a
history.replaceState(null, '', '#b') #a
clicking <a href="#b"> #b
location.assign('#b') #b
location.replace(location.href) #b
navigation.navigate('#b') #b
location.hash = ''; location.hash = '#b' #b
history.back() / history.forward() the entry's #hash
The last line surprises people: moving through history entries made by
pushState() does update :target, because a
history traversal counts as a navigation. So the wrong element appears after a click
in your app, then the right one appears when the user presses Back and Forward.
Gotcha: setting location.hash to the same value does nothing
The usual advice is to use location.hash instead of
pushState(). That works only if the hash is actually changing. If the
router has already pushed #b, this is a no-op:
history.pushState(null, '', '#b');
location.hash = '#b'; // the URL already ends in #b, so nothing happens
document.querySelector(':target').id; // "a"
The location.hash setter returns early when the new fragment equals the
current one, so there's no navigation and no hashchange event. Setting
it to '' first and then to '#b' works, but it adds two
history entries and fires two hashchange events.
The fix: navigate to the URL you already have
location.replace(), location.assign(), setting
location.href and clicking a link don't have that early return. Given the
current URL, they do a fragment navigation, which updates :target and
scrolls to the element. location.replace() is the best of these because
it doesn't add a history entry. Use it right after your pushState():
history.pushState({ page: 'install' }, '', '#install');
location.replace(location.href);
document.querySelector(':target').id; // "install"
A fragment navigation within the same document is synchronous, so
:target is up to date on the next line. The
updateTarget() function at the top of this article adds the two fixes
for the gotchas below.
Gotcha: the navigation can wipe history.state
The fragment navigation reuses the current history entry, but browsers disagree about
its state object. In my tests, Chromium kept the object passed to
pushState(), while Firefox reset history.state to
null:
history.pushState({ page: 'install' }, '', '#install');
location.replace(location.href);
history.state; // Chromium: { page: 'install' } Firefox: null
Routers often store data in history.state, so save it before the
navigation and restore it with replaceState() afterwards, as
updateTarget() does.
Gotcha: location.replace(location.href) reloads a URL without a hash
The navigation only stays on the page when the URL has a fragment. If your router
pushed a URL without one, for example going back to /docs, then
location.replace(location.href) is an ordinary navigation and reloads
the page.
To clear :target in that case, navigate to an empty fragment with
location.replace('#'). That stays on the page and leaves
:target matching nothing, but it adds a # to the end of the
URL. The replaceState() call in updateTarget() removes it.
Gotcha: Chromium fires popstate during the fix
In Chromium 159, the location.replace() call fires a
popstate event with event.state set to null,
before updateTarget() restores the state. When clearing the hash it also
fires a hashchange event. Firefox 159 fired neither. If your router
handles popstate as a Back or Forward press, ignore the one you caused.
The event is dispatched synchronously, so a flag works:
let updatingTarget = false;
function updateTarget() {
updatingTarget = true;
try {
const state = history.state;
if (location.hash) {
location.replace(location.href);
} else {
location.replace('#');
}
history.replaceState(state, '', location.href.replace(/#$/, ''));
} finally {
updatingTarget = false;
}
}
addEventListener('popstate', (event) => {
if (updatingTarget) {
return;
}
// handle Back and Forward
});
Alternative: track the target with a class
If you'd rather not navigate at all, don't rely on :target. Mark the
element yourself whenever the URL changes, and select the class instead:
function markTarget() {
for (const el of document.querySelectorAll('.is-target')) {
el.classList.remove('is-target');
}
const id = decodeURIComponent(location.hash.slice(1));
document.getElementById(id)?.classList.add('is-target');
}
history.pushState(null, '', '#install');
markTarget();
document.querySelectorAll('.is-target'); // NodeList [p#install]
Call markTarget() after every pushState() or
replaceState(), and on popstate. In CSS, use
:is(:target, .is-target) so the style still works on the first page load
and with JavaScript off. The downside is that you lose the scroll to the element,
which updateTarget() gives you for free.
Try it in your browser
The buttons below change this page's URL, then show which element
:target matches. Highlighted items match :target.
#demo-one
#demo-two
Results will appear here.
Press the first button, then the second: the URL changes to
#demo-two but the highlight stays on #demo-one. Press
updateTarget() to fix it.
Summary
-
:targetmatches the document's target element, which only changes on a navigation.pushState()andreplaceState()aren't navigations, soquerySelectorAll(':target')keeps returning the old element. -
Back and Forward do update
:target, even between entries created bypushState(). -
Setting
location.hashto the hash the URL already has does nothing.location.replace(location.href)does a navigation that updates:targetwithout adding a history entry. -
Save and restore
history.statearound it (Firefox resets it), uselocation.replace('#')when there's no hash (otherwise the page reloads), and ignore thepopstatethat Chromium fires. -
Or skip
:targetand select an.is-targetclass that you manage yourself.