Scoped selection searches inside one container; global selection searches the whole document — and in Drupal the decision is usually made for you, because the same component can appear on a page more than once and you will not be told when it does.
That is what makes it a correctness question rather than a style question. A site builder can place the same block into three regions, embed a Views display twice, add a Paragraph type five times to one node, or drop any of those anywhere with Layout Builder. None of it reaches your JavaScript as a warning. It arrives as a bug report saying "the tabs at the bottom of the page open the ones at the top."
The bug that makes the decision for you
Take a tabbed component. A global implementation collects every tab pane on the page:
const panes = document.querySelectorAll('.tabs-pane');
const buttons = document.querySelectorAll('.tabs-button');
With one instance that is correct and simple. With two, panes holds the panes of both components, so clicking a tab in the second instance closes the panes in the first — the "hide everything, then show one" step hides everything on the page. The failure is also invisible during development, where you almost always build with a single instance in front of you.
The same trap has a Drupal-flavoured cousin: duplicate IDs. If your Twig template hard-codes id="tabs-pane-1", two instances produce two elements with the same ID, document.getElementById() returns whichever the parser saw first, and the markup is invalid HTML into the bargain. This is the same class of problem as the one behind Drupal blocks vs block content and why your paragraphs are duplicating — one authored thing, several rendered copies, and code that assumed there would be one.
Scoped selection, in practice
Every query starts from a container element rather than from document. The container is passed in; nothing inside the function cares what else is on the page.
function handleTabClick(tabContainer, event) {
const button = event.target.closest('.tabs-button');
if (!button) return;
// Every lookup below is bounded by tabContainer.
const panes = tabContainer.querySelectorAll('.tabs-pane');
const buttons = tabContainer.querySelectorAll('.tabs-button');
const pane = tabContainer.querySelector(`#${paneIdFor(button)}`);
if (!pane) return;
panes.forEach((p) => { p.style.display = 'none'; p.setAttribute('aria-hidden', 'true'); });
buttons.forEach((b) => b.setAttribute('aria-selected', 'false'));
pane.style.display = 'block';
pane.setAttribute('aria-hidden', 'false');
button.setAttribute('aria-selected', 'true');
}
Note the third lookup: even the ID is resolved with tabContainer.querySelector('#…'), not document.getElementById(). That way a duplicated ID degrades into "nothing happens here" instead of "the wrong instance responds" — a far cheaper bug to diagnose.
Why :scope > matters once components nest
A container is not enough on its own if the component can contain another copy of itself — a tab pane holding a Views block that is itself tabbed, which happens more often than you would like. container.querySelector('.inner') searches all descendants and will reach into the nested instance. The :scope pseudo-class anchors the selector to the element you called the method on:
// Only the direct child wrapper, never a nested instance's wrapper.
this._inner = this.querySelector(':scope > .vvjt-inner');
That line is from js/vvjt-tabs-element.js in VVJ Tabs, a Views display-format module I maintain. One extra token, and it is the difference between a component that can be nested and one that cannot.
Where global selection is still the right answer
Scoping is not a rule to apply everywhere. Three cases genuinely call for a document-wide reach:
- Genuinely page-level singletons. A skip link, a back-to-top button, the one status-message region. There is one per document by definition, and pretending otherwise adds ceremony for nothing.
- Cross-component coordination. Closing every open dropdown on Escape requires knowing about all of them. Do it by dispatching an event on
documentthat each instance listens for, not by reaching into other instances' internals. - Browser APIs that are only global.
document.startViewTransition()animates the document; there is no scoped version. Even a strictly scoped component calls that one ondocument.
The test I use is simple: if a second copy of this component appeared on the page, would this line still be correct? If yes, global is fine. If no, scope it.
The Drupal layer everyone forgets: context and once()
This is the part that turns a working component into an intermittent one. Drupal does not run your JavaScript once on page load. Drupal.attachBehaviors() runs on load, and then again after every AJAX response, every BigPipe placeholder that arrives, every Views exposed-filter refresh and every off-canvas dialog. Core's own documentation in core/misc/drupal.js spells out the contract: behaviours should use once('behavior-name', selector, context) so that a behaviour attaches only once to a given element.
Drupal.behaviors.myTabs = {
attach(context) {
// `context` is the new fragment on an AJAX response, `document` on load.
once('my-tabs', '.tabs-wrapper', context).forEach((container) => {
container.addEventListener('click', (e) => handleTabClick(container, e));
});
},
};
Two mistakes are worth naming because both look fine in testing:
- Querying
documentinstead ofcontext. On an AJAX refresh the behaviour re-processes the whole page, not just the new fragment. With a missingonce()as well, you attach a second click listener to every existing element and the component starts firing twice, then three times. - Skipping
once()because "it only runs on load." It does, until someone enables BigPipe or adds a pager, and then it runs again with no code change of yours to blame.
They solve two halves of one problem: once() stops you binding twice, scoping stops you binding to the wrong thing. You need both. The same discipline shows up in form widgets — it is the approach behind Selectify's five custom form elements.
Side by side
| Concern | Scoped selection | Global selection |
|---|---|---|
| Multiple instances on a page | Correct by construction | Breaks silently |
| Duplicate IDs in markup | Degrades to a no-op in that instance | Wrong instance responds |
| Nested instances | Safe with :scope > | Unsafe |
| Search cost | Bounded by the subtree | Whole document each call |
| Drupal AJAX and BigPipe | Pairs naturally with context | Re-processes the whole page |
| Code overhead | Container must be passed or held | None |
| Best fit | Anything a site builder can place twice | Page singletons and document-level APIs |
How I removed the choice entirely
In VVJ Tabs 1.x the container was a function parameter, exactly as above. That worked, but it relied on every future contributor threading it through. In 2.x the component is a custom element, <vvjt-tabs>, and the container stops being a parameter because it is this. Three consequences are worth stealing even if you never write a custom element:
- Scope becomes structural. There is no
documentto reach for by accident; the natural thing to type isthis.querySelector(). - Teardown becomes automatic. Every listener is registered with
{ signal: this.signal }from anAbortControllerthatdisconnectedCallback()aborts. When Drupal's AJAX replaces the markup, the listeners go with it — nodetachbookkeeping. - Re-attachment stays explicit. After revealing a pane the element calls
Drupal.attachBehaviors(activePane, drupalSettings), so a nested Views block or field group inside it wakes up. That is the one place a component legitimately reaches outward, and passing the pane rather than document keeps even that scoped.
What is left of Drupal.behaviors does nothing but mark the elements with once(). Everything else lives in the element's own lifecycle.
Common questions
Can I just use unique IDs from the Twig template instead?
You should generate unique IDs anyway, because duplicates are invalid HTML and break aria-controls and aria-labelledby. But unique IDs plus global lookups still leave you doing string surgery to work out which instance you are in. Scoping removes the question instead of answering it.
What about jQuery's $(selector, context)?
Same idea, and it worked. The reason not to reach for it in new Drupal code is that jQuery is no longer a given, and pulling it in solely to scope a query is a large bill for one argument. element.querySelectorAll() is the same operation with no dependency.
Does any of this affect accessibility?
Directly. The attributes that make a tab set usable — aria-selected, aria-expanded, aria-controls, roving tabindex — are all per-instance state. A global implementation sets them on every instance at once, so a screen reader is told two different tabs are selected. If you are already thinking about announcements, ARIA live regions for Drupal 11 system messages covers the other half of that problem.
How do I test for this without building a second instance by hand?
Place the block twice in different regions, or add a second Views embed, then drive the first instance and watch the second. If you can, nest one inside the other — that catches the descendant-versus-child bug that plain scoping misses.
Next step
Open the most interactive component on your site and check three things: does it query document, does its behaviour use context, and does it call once()? Any one of those missing is a bug waiting for a site builder to trip it.
If you would rather someone else made that pass, this is the kind of Drupal development work I do, and a quote needs only a short description — what the component is, how many can appear on a page, and what it currently does wrong.