JQUERY Tutorial: Element Selector šŸŽÆ

beginner
22 min

JQUERY Tutorial: Element Selector šŸŽÆ

Welcome to our comprehensive guide on JQuery's Element Selector! In this tutorial, we'll dive deep into understanding how to select HTML elements using JQuery, making your web development journey more efficient. šŸ’”

Why JQuery?

JQuery simplifies HTML document traversing, event handling, and animating. It's an indispensable tool for modern web development due to its ease of use and compatibility with multiple browsers.

Understanding Element Selectors

Element selectors in JQuery allow you to select HTML elements based on their type, ID, class, attribute, or even complex combinations. Let's explore some basic selectors! šŸ“

1. Simple Selector

To select an element, we use its tag name.

html
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1 id="myHeader">This is a Heading</h1> <p id="myParagraph">This is a Paragraph.</p> <script> $(document).ready(function(){ $('h1').css('color', 'red'); // Changing h1 color to red }); </script> </body> </html>

šŸ“ Note: $() is the shortcut to jQuery and document.ready ensures our code runs only when the document is fully loaded.

2. ID Selector

To select an element based on its ID, we use the # symbol followed by the ID.

html
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1 id="myHeader">This is a Heading</h1> <p id="myParagraph">This is a Paragraph.</p> <script> $(document).ready(function(){ $('#myHeader').css('color', 'red'); // Changing heading color to red }); </script> </body> </html>

3. Class Selector

To select an element based on its class, we use the . symbol followed by the class name.

html
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1 id="myHeader" class="myClass">This is a Heading</h1> <p id="myParagraph" class="myClass">This is a Paragraph.</p> <script> $(document).ready(function(){ $('.myClass').css('color', 'blue'); // Changing class color to blue }); </script> </body> </html>

Quiz Time

Quick Quiz
Question 1 of 1

Which of the following JQuery selectors is used to select an HTML element based on its class?

Stay tuned for the next lesson where we'll delve deeper into advanced JQuery selectors! šŸ“