jQuery Selectors

In this blog, we will learn different type selectors in jQuery and how to use jQuery selectors in a webpage.

Introduction

 
We use selectors for finding elements from the DOM and we will manipulation that element. There are various types of selectors. Each selector starts with dollar ($) symbol and round brackets. 
 

Types of jQuery Selectors

There are 3 types of selectors:
  • Element selector
  • Id selector
  • Class selector 

Element selector

 
It will select an element using the element name.
 
Example:
  1. $("div").hide();  
All <div> will be hidden from the page.
 

Id selector 

 
In scripting language, we use '#' as the symbol of id. We can use once a particular name as id in a single page. 
 
Example: 
  1. $("#divUnused").hide();  
The element id with #divUnused will be hidden.
 

Class selector

 
In scripting language, we use '.'  as the symbol of class. We can use a name as many times in a single page.
  1. $(".divUnused").hide();  
The element class with .divUnused will be hidden.
 

jQuery Selectors Code Examples

  1. $("*").hide();  
The above code will hide all the elements from the page.
  1. $(".p").click(function(){  
  2.    $(this).hide();  
  3.  });  
The above code will hide all the elements with class name 'P'  from the page. It is known as 'this' selector. If we will use '$(this)' inside any jQuery function then that will choose the curent selector.
  1. $("p.intro").hide();  
The above code will hide all the 'p' element having the class name 'intro'.
  1. $("p:first").hide();  
The above code will hide the first 'p' element
  1. $("ul li:first").hide();  
The above code will hide the first 'li' element of the first 'ul'.
  1. $("ul li:first-child").hide();  
The above code will hide the first 'li' element of every 'ul'
  1. $("[href]").hide();  
The above code will hide all the 'href' from the page.
  1. $("a[target='_blank']").hide();  
The above code will hide all the 'a' elements where target is blank.
  1. $("a[target!='_blank']").hide();  
 The above code will hide all the 'a' elements where target is not blank.
  1. $(":button").hide();  
The above code will select all the buttons where input type="button".
  1. $("tr:even").hide();  
The above code will hide all the even rows from a table.
  1. $("tr:odd").hide();  
The above code will hide all the odd rows from a table.
 

Summary 

 
In this blog and code examples, I discussed types of jQuery selectors and how to use them in our application. I hope this blog helps you understand jQuery selectors.