YouTip LogoYouTip

Sel Parent Child

## jQuery `parent > child` Selector The jQuery `parent > child` selector is a hierarchical selector used to target and select elements that are the **direct children** of a specified parent element. Unlike the descendant selector (which selects all matching elements down the entire DOM tree), the child selector only looks at the immediate next level of the DOM hierarchy. --- ## Definition and Usage The `("parent > child")` selector selects all elements specified by `child` that are direct children of the element specified by `parent`. ### Key Difference: Child vs. Descendant * **`parent > child` (Child Selector):** Only selects elements that are directly nested inside the parent (1 level deep). * **`parent child` (Descendant Selector):** Selects all matching elements nested anywhere inside the parent, including grandchildren, great-grandchildren, etc. (any level deep). --- ## Syntax ```javascript $("parent > child") ``` ### Parameters | Parameter | Type | Description | | :--- | :--- | :--- | | `parent` | *Required* | Any valid jQuery selector representing the parent element. | | `child` | *Required* | Any valid jQuery selector representing the direct child element to be selected. | --- ## Code Examples ### Example 1: Basic Usage (Selecting Direct `` Elements) In this example, we select only the `` elements that are direct children of a `
` element and apply a CSS style to them. ```html
This span is a direct child of div (will be highlighted).

This span is inside a paragraph, which is inside the div (will NOT be highlighted).

``` ### Example 2: Selecting Direct `
  • ` Elements in Nested Lists This example demonstrates how to select only the top-level list items (`
  • `) of a specific unordered list (`
      `), without affecting nested list items. ```html
      • Top-level Item 1 (will have a red border)
      • Top-level Item 2 (will have a red border)
        • Nested Item A (will NOT have a red border)
        • Nested Item B (will NOT have a red border)
      • Top-level Item 3 (will have a red border)
      ``` --- ## Technical Considerations 1. **Performance:** The child selector (`parent > child`) is generally faster than the descendant selector (`parent child`) because the browser engine only needs to traverse one level down the DOM tree rather than searching recursively through all nested elements. 2. **CSS Compatibility:** This selector is based on the standard CSS child combinator (`>`). jQuery utilizes the browser's native `querySelectorAll()` engine where available, ensuring high performance. 3. **Chaining:** You can chain this selector with other jQuery methods (e.g., `.addClass()`, `.click()`, `.hide()`) to easily manipulate the selected child elements.
  • ← Sel EqSel Onlyoftype β†’