Basic Selectors in JQuery


In my previous article, we saw how to get started with JQuery, what references need to be added before writing JQuery and saw a basic selector for a paragraph HTML element. This one is another small article for Beginners in JQuery.

In this article we'll look in brief, the very basic selectors that can be used to access HTML elements in various ways. Following is the HTML markup that would be used throughout the article.

 <html>
 <head>
   <title>jQuery demo</title>
   <script type="text/javascript"   src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
   <script>
// Write your JQuery code here

   </script>
 </head>
 <body>
   <p id="paragraph1">This is first paragraph</p>
   <p id="paragraph2">This is second paragraph</p>
   <p id="paragraph3">This is third paragraph</p>
   <p id="paragraph4">This is fourth paragraph</p>
 </body>
 </html>

1) Selecting all paragraph elements:

With JQuery you can select all the elements of on type at once and operate on them. Here, we'll select all the paragraph elements and hide them.

Code

$("p").hide();

$("p") : This part of the code selects all the paragraph elements in the markup

.hide() : This method operates on all the elements selected from the selector(here, all the paragraph) and hides them

2) Selecting an element through its ID: 

We can select an HTML element through its ID

Code:

$("#paragraph1").hide();

To select an element through its ID we use "#" followed by its ID. This will select 'paragraph1' and hide that element.

3) Select First, Last, Odd and Even numbered elements:

Here we have 4 paragraph elements. We can write JQuery to select First, Last, Even numbered or odd numbered paragraphs

$("p:first") : Selects the first paragraph element in the markup
$("p:last") : Selects the last paragraph element in the markup
$("p:even") : Selects even numbered paragraph elements ie 'paragraph2' and 'paragraph4'
$("p:odd") : Selects odd numbered paragraph elements ie 'paragraph1' and 'paragraph3'

Note: Even and odd selectors are not based on the ID of the element. These selectors parse through all the paragraph elements and select the appropriate odd or even paragraph elements based on their placement in the markup

4) Select all the elements in the markup: 

$("*")

These were some of the very basic selectors in JQuery. In the next one, we'll get into more selectors and also operations that can be performed on the selected elements.

Up Next
    Ebook Download
    View all
    Learn
    View all