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 selectorId selectorClass selector .
Element selector
It will select an element using the element name.
Example:
$("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.
$("#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.
$(".divUnused").hide();
The element class with .divUnused will be hidden.
jQuery Selectors Code Examples
$("*").hide();
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 current selector.
$("p.intro").hide();
The above code will hide all the 'p' element having the class name 'intro'.
$("p:first").hide();
The above code will hide the first 'p' element
$("ul li:first").hide();
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'
$("[href]").hide();
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.
$(":button").hide();
The above code will select all the buttons where input type="button".
$("tr:even").hide();
The above code will hide all the even rows from a table.
$("tr:odd").hide();
The above code will hide all the odd rows from a table.