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. š”
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.
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! š
To select an element, we use its tag name.
<!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.
To select an element based on its ID, we use the # symbol followed by the ID.
<!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>To select an element based on its class, we use the . symbol followed by the class name.
<!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>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! š