10 Example of jQuery Selectors for Web Developers

I am primarily a Java developer but I have done a lot of work with Java web application including Servlet, JSP, and JavaScript on the client side. It was difficult for me to perform client side validation using JavaScript but ever since I come to know about jQuery, I simply love to do more validation and other stuff on the client side. The jQuery gives you immense power to do things with HTML pages and half of that power comes from its CSS-like selector engine, which allows you to select any element or group of elements from HTML page and then do things with them e.g. changes their style or behavior. For example, you can grab the divs and hide them, you can grab the buttons and make them clickable and so on. In order to learn jQuery, you need to learn its selector engine and in this tutorial, I am going to share you 10 good examples of different jQuery selectors e.g. ID selector to select single HTML element, the class selector to select group of an element and * wildcard to select all elements. Since jQuery supports many types of a selector, some of them I didn't even know, it's good to know as much as possible about them.


So here is the list of 10 jQuery selector I am going to share with you guys:
1) id selector
2) class selector
3) tag selector
4) descendant selector
5) child selector
6) pseudo-class selector
7) multiple selectors
8) not selector
9) all selector
10) has selector

Now, let's see some examples of each of these jQuery selectors and when to use which jQuery selector



jQuery ID selector Example
Id selector is one of the most used jQuery selectors and used to select just one specific element from a page. For example, $("#main") will return the HTML element with id as main. just like CSS, you need to use # (hash) to select element with their IDs. It's also the fastest selector and if you can use then always prefer ID selector. They are also very popular in jQuery interviews and you will always see one more two questions from ID selector.

examples:

// Select HTML element with id as main e.g. div id="main"
$("#main") will 

// Select HTML element with id as guess_box e.g. div id="guess_box"
$("#guess_box") will 


jQuery class selector Example
The class selector is another most common jQuery selector and used to select a group of elements from HTML page. If you remember, the class is used to style elements in jQuery but it can also use to group related elements together in jQuery even if they don't have any style. Just like in CSS, a class selector is started with a . (dot) e.g. $(".active") will return all elements from page which has class="active".

Here is a couple of examples of jQuery class selector:

// select all elements with class as active e.g. all divs
$(".active")

// select all elements with class as clickable e.g. all clickable divs
$(".clickable") 

If you remember the $() is a shortcut of jQuery() method and if you use jQuery you may get the error like "Uncaught ReferenceError: $ is not defined" if the browser is not able to load the jQuery properly.


jQuery tag selector Example
The jQuery tag selector, also known as element selector selects all the specified element from the HTML page. For example, $("p") will select all paragraphs and $("div") will select all divs. Internally tag selector calls the getElementsByTagName() function to return the appropriate elements from DOM.

// select all span elements
$("span");


jQuery descendant selector Example
The descendant selector selects all elements that are descendants of a given ancestor. The format of this selector is $(ancestor descendant) where ancestor is any valid selector and descendant is a valid selector to filter descendant elements. For example, $( "form input" ) will return any input which are descendant of form element i.e. they are inside any form.  See Head First jQuery to learn more about advanced selector in jQuery.

// select all span elements which are descendant of divs
$("div span")


jQuery child selector Example
The child selector is similar to descendant selector but it only return the direct child. It has format of $(parent > child) , for example $("div > span") will return all span which are direct child of div elements.

// select all <b> elements which are direct child of <p>
$("p > b")


jQuery pseudo class selector Example
The :even,  :odd, :checked are examples of pseudo selectors, they are not part of CSS specification but extension of jQuery to provide convenience e.g. you can use :even to select even elements (zero indexed) e.g. even rows in table to style them differently. Similarly, :odd can be used to select :odd elements in DOM tree and :checked can be used to find check elements e.g. checked radio buttons or check boxes. See jQuery in Action to learn more how pseudo selector works in jQuery.

// change the background color of even rows
$( "tr:even" ).css( "background-color", "#bbf" );

// change the background color of odd rows
$( "tr:odd" ).css( "background-color", "#bb0" );



jQuery multiple selector Example
The multiple selector is nothing but combining more than one selector in single search e.g. $(selector1, selector2, selector3) is a multiple selector which selects the combined results of all the specified selectors. For example, $( "div, span, p" ) will select all div, span, and p elements from the DOM. Remember, individual selectors are separated by comma.

//select all div and span
$( "div, span )


jQuery not selector Example
The :not() jQuery selector selects all elements except the specified element. This is mostly used together with another selector to select everything except the specified element in a group e.g. select all checkboxes which are unchecked, or select the input types which are empty.  See jQuery:Novice to Ninja to learn more about how to use not selector in JavaScript

// select all checkboxes which not checked
$(input[type=checkbox]:not(:checked))


jQuery all selector Example
The all or universal selector is used to select all elements e.g. $(*) will select all elements from HTML page. This is useful when you want to apply a style to all elements of HTML page. Btw, just be careful The all, or universal, selector is extremely slow, except when used by itself.

// select all HTML elements
$(*)


jQuery has selector Example
The :has() selector selects all elements that have one or more elements inside of them, that matches the specified selector. For example $("b:has(h1)") will select all <b> elements than have <h1> element inside of them.

// select all p which has span under it
$("p:has(span)")




That's all about 10 examples of jQuery selectors for web developers. I am sure you have learned a couple of new things today. Though most of them times you would find yourself using just class and id selector, knowing different types of selector will help you to use jQuery more effectively. Always remember to use the most specific selector to gain the best performance from jQuery. For example, using input[type=radio]:checked is more specific than just using :radio :checked.


Related jQuery tutorials you may like
  • How to get current URL, Parameters and Hash using jQuery? (solution)
  • How to use more than one jQuery UI DatePicker in JSP page? (example)
  • How to create tab-based UI using jQuery? (example)
  • How to redirect a page URL using jQuery and JavaScript? (solution)
  • How to write HelloWorld in jQuery? (solution)
  • 5 Books to learn jQuery for Web developers (books)
  • How to load jQuery in a web page? (solution)
  • Difference between jQuery document.ready() and JavaScript window.onload event? (answer)

Reference
https://api.jquery.com/category/selectors/


1 comment:

  1. Why $(selector)? // JQUERY

    document.querySelectorAll(selector) // Native Javascript.

    There same.

    ReplyDelete