jQuery Selectors
Understanding jQuery Selectors
Section titled “Understanding jQuery Selectors”jQuery selectors are a fundamental feature, allowing you to find and interact with HTML elements on a web page efficiently.
What are jQuery Selectors?
Section titled “What are jQuery Selectors?”jQuery selectors provide a powerful way to select specific HTML elements from the Document Object Model (DOM). Once selected, you can manipulate these elements (e.g., change style, content, or behavior).
Selectors use syntax primarily based on standard CSS selectors (like those for element names, IDs, classes, attributes) but also include custom jQuery extensions for more advanced selections. This makes them familiar to anyone who knows CSS.
All jQuery selections start with the dollar sign $ followed by parentheses (), enclosing the selector string: $(selector). This $ function is an alias for jQuery.
Note: Modern JavaScript offers built-in methods like document.querySelector() and document.querySelectorAll() which provide similar functionality without needing the jQuery library. However, jQuery selectors remain concise and powerful, especially within projects already using jQuery.
The Element Selector
Section titled “The Element Selector”Selects all elements matching a specific HTML tag name.
To select all <p> (paragraph) elements on a page:
$("p")Example: Hide all paragraphs when a button is clicked.
// Wait for the DOM to be fully loaded$(function() { // Select the button and attach a click event handler $("button").on('click', function() { // Select all paragraph elements and hide them $("p").hide(); });});Best Practice: Using $(function() { ... }); is the modern shorthand for $(document).ready(function() { ... });. Using .on('click', ...) is the preferred way to attach event listeners.
The ID Selector (#id)
Section titled “The ID Selector (#id)”Selects a single element based on its unique id attribute.
An id should be unique within an HTML document. Use the ID selector when targeting one specific element.
To find an element with id="main-content", use a hash character (#) followed by the ID:
$("#main-content")Example: Hide the element with id="test" when a button is clicked.
$(function() { $("button").on('click', function() { // Select the element by its ID and hide it $("#test").hide(); });});The Class Selector (.class)
Section titled “The Class Selector (.class)”Selects all elements that have a specific class attribute.
To find elements with class="highlight", use a period (.) followed by the class name:
$(".highlight")Example: Hide all elements with class="test" when a button is clicked.
$(function() { $("button").on('click', function() { // Select all elements with the class 'test' and hide them $(".test").hide(); });});More jQuery Selectors Examples
Section titled “More jQuery Selectors Examples”jQuery supports a wide range of selectors, combining CSS standards with its own extensions:
$("*"): Selects all elements on the page. Use with caution due to performance implications.$(this): Inside an event handler, selects the HTML element that triggered the event.$("p.intro"): Selects all<p>elements specifically having the classintro.$("p:first"): Selects the very first<p>element found in the document.$("ul li:first-child"): Selects the first<li>element within each<ul>.$("ul li:first"): Selects only the first<li>element of the first<ul>found.$("[href]"): Selects all elements possessing anhrefattribute (e.g.,<a>,<link>).$("a[target='_blank']"): Selects all<a>elements whosetargetattribute is exactly_blank.$("a[target!='_blank']"): Selects all<a>elements whosetargetattribute is not equal to_blank.$(":button"): Selects all<button>elements and<input>elements withtype="button".$("tr:even"): Selects even-indexed table rows (<tr>), starting from index 0 (0, 2, 4…). Useful for zebra-striping tables.$("tr:odd"): Selects odd-indexed table rows (<tr>) (1, 3, 5…).$("p:contains('Hello')"): Selects all<p>elements containing the text ‘Hello’.$("input:visible"): Selects all<input>elements that are currently visible.
For a comprehensive list, refer to the official jQuery Selectors documentation.
Organizing Code in Separate Files
Section titled “Organizing Code in Separate Files”For maintainability and better organization, especially in larger projects, place your jQuery (and general JavaScript) code in separate .js files.
Instead of embedding scripts directly in <head> or <body>, link to your external file using the src attribute in a <script> tag. Ensure you load the jQuery library before your custom script file.
<head> <!-- Load jQuery from a CDN (Content Delivery Network) --> <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<!-- Load your custom script file --> <script src="scripts/my_jquery_functions.js"></script></head>Using a CDN is recommended for loading libraries like jQuery as it leverages browser caching and distributed servers for faster loading.