## jQuery :lang() Selector
The jQuery `:lang()` selector is a powerful tool used to select elements based on their specified language attribute (`lang`). This is particularly useful for building multi-lingual websites, applying localized styling, or manipulating content dynamically based on the user's language settings.
---
## Definition and Usage
The `:lang()` selector selects elements that have a `lang` attribute matching the specified language code.
### Key Rules:
* **Exact Match:** It matches elements where the `lang` attribute is an exact match for the specified language code (e.g., `lang="en"`).
* **Subcode Match:** It also matches elements where the `lang` attribute starts with the specified language code followed immediately by a hyphen `-` (e.g., `lang="en-us"` or `lang="en-gb"`).
* **Inheritance:** Unlike simple attribute selectors (like ``), the `:lang()` selector is aware of language inheritance. If a parent element has a `lang` attribute, its child elements will also be selected by `:lang()` unless they explicitly override it with a different language attribute.
---
## Syntax
```javascript
$(":lang(language)")
```
### Parameters:
* **`language`** *(Required)*: A string specifying the language code to search for (e.g., `"en"`, `"it"`, `"zh"`).
---
## Code Examples
### Example 1: Basic Usage
The following example demonstrates how to select and style all `
` elements that are written in Italian (`it`).
```html
Hello! This paragraph is in English.
Ciao! Questo paragrafo Γ¨ in italiano.
Ciao! Questo paragrafo Γ¨ in italiano svizzero (Swiss Italian).
Bonjour! Ce paragraphe est en franΓ§ais.
```
### Example 2: Language Inheritance
The `:lang()` selector is smart enough to recognize inherited languages. In this example, the child `
` inherits the language of its parent ``.
```html
This is a paragraph.
This span inherits the French language attribute from the parent div.
```
---
## Considerations & Best Practices
1. **Attribute Selectors vs. `:lang()`**:
* The attribute selector `` only matches elements that *explicitly* have the `lang="en"` attribute defined on themselves.
* The `:lang(en)` selector is much more robust because it matches subcodes (like `en-us`) and respects HTML language inheritance down the DOM tree.
2. **Case Insensitivity**: Language codes in HTML are case-insensitive, and jQuery's `:lang()` selector handles them accordingly.
3. **Performance**: Since `:lang()` relies on traversing the DOM to check for inherited language attributes, it is recommended to prefix it with a tag name (e.g., `p:lang(en)` instead of just `:lang(en)`) to optimize selector performance.