ID Selector in jQuery 🎯

beginner
18 min

ID Selector in jQuery 🎯

Welcome to our deep dive into understanding the powerful ID Selector in jQuery! This tutorial is designed for both beginners and intermediates, so let's get started.

What is an ID Selector? 📝

An ID Selector is a CSS selector that selects an HTML element based on its unique ID. In jQuery, you can use the # symbol followed by the ID of the element you want to select.

javascript
// Example HTML structure <div id="myDiv">This is myDiv</div>
javascript
// Example jQuery code $('#myDiv').hide(); // Hides the div with id 'myDiv'

Why use an ID Selector? 💡

  • Unique selection: Since every ID is unique within a document, you can select exactly one element using an ID Selector.
  • Efficient: Finding an element by its ID is one of the quickest ways to search the DOM, as jQuery immediately locates the element without needing to search through multiple elements.

Using ID Selector in jQuery 🎯

Basic Usage

To use an ID Selector in jQuery, simply write the # symbol followed by the ID of the element you want to select.

javascript
$('#myDiv') // Selects the div with id 'myDiv'

Common Methods

Here are some common methods that you can use with ID Selectors in jQuery:

.show() 📝

Reveals the selected elements.

javascript
$('#myDiv').show();

.hide() 📝

Hides the selected elements.

javascript
$('#myDiv').hide();

.toggle() 📝

Shows the selected elements if they are hidden and hides them if they are visible.

javascript
$('#myDiv').toggle();

Practical Example 🎯

Let's say we have a form with an ID #myForm. We want to submit the form using jQuery when the user clicks on a button with the class .submit-btn.

html
<form id="myForm"> <!-- Form fields here --> </form> <button class="submit-btn">Submit</button>
javascript
$('.submit-btn').click(function() { $('#myForm').submit(); });

Quiz 💡

Quick Quiz
Question 1 of 1

What does the `#` symbol represent in jQuery?

That's it for today! We hope you've enjoyed learning about ID Selectors in jQuery. Stay tuned for more tutorials on jQuery and other web development topics! 🚀