What is a Query Selector?
Using Query Selectors in jQuery
jQuery provides a simple way to use query selectors with the $ (dollar sign) function. This function takes a query selector as its argument and returns a jQuery object that represents the selected elements. Here’s an example:
// Select all paragraphs in the document var paragraphs = $('p');
You can also chain multiple actions together using the dot (.) notation. For example, you can select all paragraphs, hide them, and then show them after 3 seconds:
// Select all paragraphs, hide them, and show them after 3 seconds $('p').hide().delay(3000).show();
Performing Actions on Selected Elements
Once you’ve selected elements using a query selector, you can perform various actions on them. Some common actions include:
- Adding or removing classes: addClass(), removeClass(), and toggleClass().
- Modifying attributes: attr() and removeAttr().
- Modifying CSS properties: css().
- Manipulating HTML content: html(), text(), append(), prepend(), and remove().
- Adding or removing event listeners: on() and off().
Here’s an example that selects all elements with the class ‘active’ and toggles their visibility:
// Toggle visibility of all elements with the class 'active' $('.active').toggle();
Traversing the DOM with Query Selectors
jQuery also provides methods to traverse the DOM using query selectors. Some common traversal methods include:
- Finding elements within a selection: find().
- Selecting a parent, child, or sibling element: parent(), children(), and siblings().
- Filtering a selection based on a condition: filter() and not().
Here’s an example that selects all list items within an unordered list, and adds the class ‘highlight’ to the ones with the class ‘important’:
// Select all list items within an unordered list and add the class 'highlight' to the ones with the class 'important' $('ul li').filter('.important').addClass('highlight');
Query selectors in jQuery make it easy to select elements, perform actions, and traverse the DOM. By using the powerful $ function and chaining methods together, you can manipulate your HTML documents with ease. Remember to always include the jQuery library in your project before using query selectors, and happy coding!