-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Description
I'd like to propose the introduction of two read-only properties on the Element
object:
Element.currentLang
Element.currentDir
Element.currentLang
and Element.currentDir
are read-only properties that reflect the element's current language/direction as determined by their or their closest ancestor's lang
and dir
attributes, respectively.
The primary use case is to improve i18n in custom elements, but the benefit will also be seen by frameworks that currently use a separate, non-standard context to determine these values. Exposing the current inherited language and direction will provide better localization capabilities by removing performance hurdles and eliminating the need for additional logic and special contexts.
This information isn't currently available without expensive DOM traversal. Furthermore, selectors such as Element.closest('[lang]')
will stop if they reach a shadow root, requiring recursive logic to break out of them:
// Recursive version of Element.closest() that breaks through shadow roots
function closest(selector, root = this) {
function getNext(el, next = el && el.closest(selector)) {
if (el === window || el === document || !el) {
return null;
}
return next ? next : getNext(el.getRootNode().host);
};
return getNext(root);
}
const lang = closest('[lang]', myEl).lang;
As a custom element author, it's not uncommon for users to have dozens of components on a page. It's also not impossible for a page to have multiple languages and directions. For components that require localization, the only way for them to inherit lang
and dir
is via DOM traversal or other non-standard logic. This, of course, isn't very efficient.
Being able to reference Element.currentLang
and Element.currentDir
will solve this in an elegant way using data the browser is likely already aware of.
Additional thoughts:
- It seems pragmatic to expect
lang
anddir
to pass through shadow roots. If desired, the custom element author can override it by applyinglang
ordir
to the host element or to any element within the shadow root. - This proposal doesn't address a way to listen for language/direction changes. This would be incredibly useful, but probably out of scope for discussion within this group.
- Interestingly, this is something that we can do with CSS via
:lang
and:dir
(limited support). Unfortunately, there's no clean way to discover this value with JavaScript.