Selecting Elements with jQuery
JavaScript is most commonly used to get or modify the content or value of the HTML elements on the page, as well as to apply some effects like show, hide, animations etc. But, before you can perform any action you need to find or select the target HTML element.
Selecting the elements through a typical JavaScript approach could be very painful, but the jQuery works like a magic here. The ability of making the DOM elements selection simple and easy is one of the most powerful feature of the jQuery.
Tip: The jQuery supports almost all the selectors defined in the latest CSS3 specifications, as well as it has its own custom selectors. These custom selectors greatly enhance the capabilities selecting the HTML elements on a page.
In the following sections, you will see some of the common ways of selecting the elements on a page and do something with them using the jQuery.
Selecting Elements by ID
You can use the ID selector to select a single element with the unique ID on the page.
For example, the following jQuery code will select and highlight an element having the ID attribute id="mark", when the document is ready to be manipulated.
Example
<script>
$(document).ready(function(){
// Highlight element with id mark
$("#mark").css("background", "yellow");
});
</script>
In the example above, the $(document).ready() is an event that is used to manipulate a page safely with the jQuery. Code included inside this event will only run once the page DOM is ready. We’ll learn more about the events in next chapter.
Selecting Elements by Class Name
The class selector can be used to select the elements with a specific class.
For example, the following jQuery code will select and highlight the elements having the class attribute class="mark", when the document is ready.
Example
Try this code »
<script>
$(document).ready(function(){
// Highlight elements with class mark
$(".mark").css("background", "yellow");
});
</script>
Selecting Elements by Name
The element selector can be used to select elements based on the element name.
For example, the following jQuery code will select and highlight all the paragraph i.e. the <p> elements of the document when it is ready.
Example
<script>
$(document).ready(function(){
// Highlight paragraph elements
$("p").css("background", "yellow");
});
</script>