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:
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:
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.
The element class with .divUnused will be hidden.
jQuery Selectors Code Examples
The above code will hide all the elements from the page.
- $(".p").click(function(){
- $(this).hide();
- });
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.
The above code will hide all the 'p' element having the class name 'intro'.
The above code will hide the first 'p' element
The above code will hide the first 'li' element of the first 'ul'.
- $("ul li:first-child").hide();
The above code will hide the first 'li' element of every 'ul'
The above code will hide all the 'href' from the page.
- $("a[target='_blank']").hide();
The above code will hide all the 'a' elements where target is blank.
- $("a[target!='_blank']").hide();
The above code will hide all the 'a' elements where target is not blank.
The above code will select all the buttons where input type="button".
The above code will hide all the even rows from a table.
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.