YouTip LogoYouTip

Jq Sel Target

## jQuery :target Selector The jQuery `:target` selector is a powerful tool used to select the unique active element whose `id` matches the fragment identifier (hash) of the current document's URL. This selector is highly useful for creating interactive user interfaces, such as highlighting a specific section when a user clicks an anchor link, building tabbed interfaces, or focusing on specific content dynamically. --- ## Definition and Usage The `:target` selector targets the element that is the destination of the referring URI. ### How it works: If the document's URI contains a fragment identifier or hash (e.g., `#section-2`), the `:target` selector will match the element with the corresponding `id` attribute (e.g., `
`). * **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

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.

``` --- ## 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).
← Misc CallbacksMisc Hasdata β†’

YouTip © 2024-2026 | Home | Learn Technology, Build Dreams!

All content is for educational and learning purposes only.