querySelectorAll() Returns Duplicates When a <select> Has <selectedcontent>
You've built a country picker with the new customizable <select>.
The button shows the selected option's flag and name through a
<selectedcontent> element:
<select id="country">
<button><selectedcontent></selectedcontent></button>
<option value="fr"><img class="flag" id="flag-fr" src="fr.svg" alt=""> <span class="name">France</span></option>
<option value="jp" selected><img class="flag" id="flag-jp" src="jp.svg" alt=""> <span class="name">Japan</span></option>
</select>
There are two options, but in Chrome your query finds three names:
[...document.querySelectorAll('#country .name')].map((el) => el.textContent);
// Chromium: ["Japan", "France", "Japan"]
// Firefox: ["France", "Japan"]
document.querySelectorAll('#flag-jp').length; // Chromium: 2
document.getElementById('flag-jp').closest('option'); // Chromium: null
Short answer: in browsers that support it,
<selectedcontent> contains a real copy of the selected option's
contents, made with cloneNode(). Those copies are ordinary elements, so
any query that isn't limited to options finds them too. Put option in
your selectors:
document.querySelectorAll('#country option .name'); // every option's name, in every browser
document.querySelectorAll('#country option:checked .name'); // just the selected one
Where the extra elements come from
<selectedcontent> is part of the customizable select feature. When
the selected option changes, the browser removes everything inside
<selectedcontent> and fills it with a deep clone of the new
option's child nodes. After the page above loads, Chromium's DOM looks like this:
<select id="country">
<button>
<selectedcontent>
<img class="flag" id="flag-jp" src="jp.svg" alt=""> <span class="name">Japan</span>
</selectedcontent>
</button>
<option value="fr">...</option>
<option value="jp" selected><img class="flag" id="flag-jp" ...> <span class="name">Japan</span></option>
</select>
The clone isn't in a shadow tree. It sits in the light DOM, before the options, so
querySelectorAll() finds it, and finds it first. The copy is the
option's contents rather than an <option>, so
select.options still has 2 entries, but selectors see every element.
This doesn't depend on your CSS. In my tests, Chromium 159 filled
<selectedcontent> even for a select styled with
appearance: auto, where the button isn't shown at all.
Why Chrome and Firefox give different results
Chromium-based browsers support customizable select. Firefox 159 doesn't yet: it
keeps the <button> and <selectedcontent>
elements, but leaves <selectedcontent> empty. These are the
results for the select above:
Query Chromium 159 Firefox 159
document.querySelectorAll('#country .name') 3 2
document.querySelectorAll('#flag-jp') 2 1
document.getElementById('flag-jp') is inside selectedcontent option
select.options.length 2 2
document.querySelectorAll('#country option') 2 2
So code written and tested in Firefox can break in Chrome, and code that relies on the copy (for example, reading the button's text) gets nothing in Firefox. I couldn't test Safari, so check its results with the demo below.
Queries that skip the copy
The copies are never inside an <option>, so including
option in the selector is enough:
select.querySelectorAll('option .name'); // one per option
select.querySelectorAll('option:checked .name'); // the selected option's name only
select.selectedOptions[0].querySelector('.name'); // the same, without a selector
If you can't change the selector's structure, for example in a generic helper,
exclude anything inside <selectedcontent> with
:not():
document.querySelectorAll('.name:not(selectedcontent *)');
And if you want the copy, for example to check what the button is showing, select it
directly: select.querySelector('selectedcontent .name'). Just remember
that it returns null in browsers without support.
Gotcha: getElementById() returns the copy
cloneNode() copies id attributes, so any ID inside the
selected option now appears twice. getElementById() and
querySelector('#…') return the first match in document order, and
<selectedcontent> comes before the options:
document.getElementById('flag-jp').parentElement.localName;
// Chromium: "selectedcontent" Firefox: "option"
Anything else that refers to the ID has the same problem: #flag-jp CSS
rules style both copies, and aria-labelledby or
<label for> may point to the wrong one. The simplest fix is to
not put IDs inside options. Use a class or a data- attribute and select
it with option in the selector.
Gotcha: the copy doesn't follow changes to the option
The clone is only made when the selection changes. If you edit the selected option afterwards, the button keeps showing the old content. In Chromium 159:
select.selectedOptions[0].querySelector('.name').textContent = 'Nippon';
select.querySelector('selectedcontent').textContent.trim(); // "Japan"
select.selectedIndex = select.selectedIndex; // re-select the same option
select.querySelector('selectedcontent').textContent.trim(); // "Nippon"
Re-selecting the option makes a fresh clone. Editing the copy has no effect on the option, and your edit is thrown away the next time the selection changes.
Gotcha: the copy has attributes but no event listeners
A deep clone keeps attributes, including class, data-* and
inline styles, so the copies match the same selectors as the originals. It doesn't
keep event listeners added with addEventListener(), or properties set
from JavaScript. If you loop over querySelectorAll('.name') and attach a
listener to each, the copy gets one too, but only until the next selection change
replaces it.
Gotcha: every selection change is a DOM mutation
Because the browser swaps the copy's nodes on each change, a
MutationObserver watching the page with subtree: true
receives a childList record whose target is the
<selectedcontent> each time the user picks an option. In my
test, selecting a new option produced a record with 3 removed and 3 added nodes. If
your observer re-runs querySelectorAll() to find new content, it now
runs on every selection, and finds the fresh copies as "new" elements. Ignore
records whose target is a <selectedcontent>:
new MutationObserver((records) => {
const relevant = records.filter((record) => !record.target.closest('selectedcontent'));
// ...
}).observe(document.body, { childList: true, subtree: true });
What about <select multiple>?
In Chromium 159, <selectedcontent> in a
<select multiple> stays empty, so there are no copies to worry
about. The HTML spec is
adding support for it, and
in that design the copies are whole <option> elements rather than
their contents, which the spec then excludes from select.options. Once
that ships, select.querySelectorAll('option') will include the copies,
so the option trick above won't be enough there. Use
select.selectedOptions, or add :not(selectedcontent *).
Try it in your browser
This page contains the select from the start of the article. Pick a country, then press the button to run the queries:
Results will appear here.
Summary
-
<selectedcontent>holds a real clone of the selected option's contents, in the light DOM, before the options. Any selector that doesn't require anoptionancestor finds those elements twice. - Firefox 159 doesn't support it and leaves the element empty, so the same query returns different counts in Chrome and Firefox.
-
Write
option .name,option:checked .nameor.name:not(selectedcontent *), or useselect.selectedOptions. -
Avoid IDs inside options:
getElementById()returns the copy in Chromium. -
The copy is only refreshed when the selection changes, has no event listeners,
and is replaced on each change, which
MutationObservers will see.