Ticker

6/recent/ticker-posts

jQuery Selectors

jQuery Selectors

jQuery provides a powerful set of selectors that allow you to select and manipulate HTML elements on a web page. Selectors are used to target specific elements based on their tag names, class names, IDs, attributes, and more. This documentation will cover some commonly used jQuery selectors along with their code examples and explanations.

1. Tag Selectors

Tag selectors allow you to select elements based on their HTML tag names. They are represented using the tag name itself. Here's an example:

javascript
// Select all <p> elements $('p').css('color', 'red');

Explanation: The above code selects all <p> elements on the page and changes their text color to red using the css() method.

2. Class Selectors

Class selectors are used to select elements based on their CSS class names. They are represented using a dot (.) followed by the class name. Here's an example:

javascript
// Select all elements with the class "highlight" $('.highlight').fadeOut();

Explanation: The above code selects all elements with the class "highlight" and fades them out using the fadeOut() method.

3. ID Selectors

ID selectors are used to select elements based on their unique IDs. They are represented using a hash (#) followed by the ID value. Here's an example:

javascript
// Select the element with the ID "myElement" $('#myElement').addClass('active');

Explanation: The above code selects the element with the ID "myElement" and adds the class "active" to it using the addClass() method.

4. Attribute Selectors

Attribute selectors allow you to select elements based on their attribute values. They are represented using square brackets ([]) and the attribute name and value. Here's an example:

javascript
// Select all <a> elements with the "target" attribute set to "_blank" $('a[target="_blank"]').text('Open in new window');

Explanation: The above code selects all <a> elements with the "target" attribute set to "_blank" and changes their text to "Open in new window" using the text() method.

5. Multiple Selectors

Multiple selectors allow you to combine different selectors together to select elements. They are represented by separating the selectors with a comma (,). Here's an example:

javascript
// Select all <input> elements and elements with the class "button" $('input, .button').prop('disabled', true);

Explanation: The above code selects all <input> elements and elements with the class "button" and disables them by setting the disabled property to true using the prop() method.

These are just a few examples of the many selectors available in jQuery. Selectors are a powerful tool that can greatly simplify the process of targeting and manipulating elements on a web page.

Post a Comment

0 Comments