`).
* **Example Scenario:**
If the current URL is `https://example.com/#intro`, the jQuery selector `$("p:target")` will select the `
` element. If the URL does not contain a hash, or if no element matches the hash, the selector will return an empty set. --- ## Syntax ```javascript $( ":target" ) ``` You can also combine it with specific element tags to narrow down the selection: ```javascript $( "div:target" ) // Selects only
elements that are currently targeted
```
---
## Code Examples
### Example 1: Highlighting a Targeted Section
This example demonstrates how to use the `:target` selector to highlight a specific paragraph when a user clicks on a corresponding navigation link.
```html
jQuery :target Selector Example
```
---
## Considerations and Best Practices
1. **CSS Alternative:**
Modern browsers natively support the CSS `:target` pseudo-class. For simple styling changes (like changing background colors or visibility), it is often more performant to use pure CSS:
```css
div:target {
background-color: #ffeb3b;
}
```
Use the jQuery `:target` selector when you need to perform complex JavaScript operations, such as fetching data via AJAX, triggering animations, or manipulating DOM structures when an element becomes targeted.
2. **The `hashchange` Event:**
The `:target` state changes when the URL hash changes. If you are writing jQuery code that relies on `:target`, make sure to bind your logic to the `$(window).on("hashchange", ...)` event so that your UI updates dynamically without requiring a page reload.
3. **Element IDs:**
Ensure that the IDs on your target elements are unique and match the hash values in your anchor links exactly (case-sensitive).
Navigation Links
Content Sections
Section 1
This is the first section of the document.
Section 2
This is the second section of the document.
Section 3
This is the third section of the document.
YouTip