Lesson 3 – Using Selectors in jQuery

jQuery allows you to select one or more HTML elements using CSS selectors. A selector in jQuery is basically a function that finds matching elements from Document Object Model (DOM) based on given criteria and by making use of various expressions. We can perform different types of operations and functions on the element once it is selected.

The $() Factory Function

You always start a jQuery function or selector with a dollar ($) sign followed by parentheses. The factory function $() either takes an html tag, or tag with a certain id or class as a parameter to select elements in any document.

In the following example, we select all the paragraph (p) tag in the document and change the text color from default that is black to red.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Selectors</title>
    [block]0[/block]

    
        $(document).ready(function() {
           $('p').css('color', 'red');
        });
     
</head>
<body>
    

This is the first paragraph

This is the second paragraph

This is the third paragraph

</body> </html>

Here is the output of the above code.

Now, we also see how to select an element with a given id and class using selectors.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Selectors</title>
    [block]1[/block]

    
        $(document).ready(function() {
           $('.paper1').css('color', 'red');
           $('#paper2').css('color', 'yellow');
        });

     
</head>
<body>
    

This is the first paragraph

This is the second paragraph

</body> </html>

Now the text color of the first and second paragraphs will be red and aqua respectively as shown in the following image.

It is imperative for you to master the art of using selectors. In fact, you are going to use them all the time while developing in jQuery. They are very useful as they help you select the exact element from the DOM without any trouble.

In the next lesson, we will discuss how to manipulate tags’ attributes and properties with the help of jQuery.