YouTip LogoYouTip

Sel Onlyoftype

## jQuery :only-of-type Selector The `:only-of-type` selector in jQuery is a powerful filtering tool used to select elements that are the **only child of their specific tag name (type)** within their parent element. Unlike `:only-child`, which requires the element to be the absolute only child of its parent, `:only-of-type` matches an element if no other siblings share the same HTML tag name, even if other types of sibling elements exist. --- ## Syntax ```javascript $("selector:only-of-type") ``` * **selector** (optional): A valid jQuery selector (e.g., `p`, `div`, `.class-name`). If omitted, it defaults to `*` (all elements), selecting any element that is the only one of its type within its parent. --- ## Definition and Usage The `:only-of-type` selector targets every element that is the unique child of its specific type under its parent. ### Key Difference: `:only-child` vs `:only-of-type` * **`:only-child`**: Matches an element only if its parent has **exactly one** child element in total. * **`:only-of-type`**: Matches an element if its parent has **no other siblings of the same tag name**. The parent can have other children of different tag names. --- ## Code Examples ### Example 1: Basic Usage with Paragraphs In this example, we select and highlight any `

` element that is the only `

` element inside its parent container. #### HTML Structure: ```html

Some text

I am the only paragraph here.

First paragraph.

Second paragraph.

``` #### jQuery Code: ```javascript $(document).ready(function(){ // Select and style the unique

element of its type $("p:only-of-type").css("background-color", "yellow"); }); ``` --- ### Example 2: Interactive Comparison This example demonstrates how `:only-of-type` behaves when multiple sibling types are present in the DOM. ```html

Paragraph 1 (Not unique, there are two paragraphs here).

Paragraph 2 (Not unique).

Span 1 (Unique! This is the only span in this div).

Paragraph 3 (Unique! This is the only paragraph in this div).

Span 2 (Unique! This is the only span in this div).
``` --- ## Technical Considerations 1. **Performance**: Because `:only-of-type` is a custom jQuery pseudo-class extension (derived from CSS3), it cannot take advantage of the performance boost provided by the native DOM `querySelectorAll()` method in some older browsers. For optimal performance in complex applications, narrow down the search by prefixing it with a tag name or class (e.g., `div.container p:only-of-type`). 2. **CSS Compatibility**: This selector mirrors the standard CSS `:only-of-type` pseudo-class. 3. **Empty Parents**: If a parent element has no children, this selector will not match anything inside it.
← Sel Parent ChildSel Nthlastoftype β†’