jQuery Prefix Selector for Language Tags
The jQuery attribute contains prefix selector
([attribute|="value"]) is a specialized tool engineered
specifically to match attributes that contain either an exact value or
that value followed immediately by a hyphen. This selector aligns
directly with the BCP 47 language tag specification (such as
en, en-US, and en-GB), allowing
developers to target, style, and manipulate elements based on a primary
language code while automatically including all regional
sub-variants.
How the Selector Works
The syntax for the selector is:
$('[attribute|="value"]')When evaluated, it matches elements where the target attribute value:
- Exactly equals the specified string (e.g.,
en), OR - Starts with the specified string followed immediately by a hyphen
(e.g.,
en-US,en-GB,en-AU).
It will not match values where the prefix continues without a hyphen,
avoiding false positives (e.g., english or
enter).
Practical Implementation
Consider the following HTML markup with mixed language tags:
<article>
<p lang="en">Standard English text.</p>
<p lang="en-US">American English text.</p>
<p lang="en-GB">British English text.</p>
<p lang="es">Texto en español.</p>
<p lang="es-MX">Texto en español mexicano.</p>
</article>To target all English content regardless of dialect, apply the prefix
selector to the lang attribute:
// Target all English variations and apply a specific style
$('p[lang|="en"]').css('font-family', '"Georgia", serif');
// Target all Spanish variations and attach a class
$('p[lang|="es"]').addClass('highlight-spanish');In this example, $('p[lang|="en"]') selects
lang="en", lang="en-US", and
lang="en-GB", but ignores all other language
variations.
Common Use Cases
- Typography and Font Swapping: Certain scripts require specific line heights, font families, or sizes to remain legible. The selector allows automated font-family switching based on the primary language family.
- Right-to-Left (RTL) Layout Adjustments: Regional
tags like
ar,ar-SA, orar-EGcan be selected collectively using$('[lang|="ar"]')to toggle direction or text-alignment properties dynamically. - Dynamic Translation Loading: Applications loading localized UI components can query the DOM for parent containers using a specific language prefix to trigger targeted translation bundles or date formatting scripts.