jQuery - SPLessons

Chapter 8

jQuery Selectors

jQuery Selectors

One of greatest strengths of jQuery is its ability to find parts of the page in an easy and reliable way. Modern web pages are often complex with hundreds of elements on a single page, so being able to easily find just what the user is looking for is crucial, and jQuery makes this a snap.
jQuery library offers number of selectors so, it is easy to select the required HTML elements based on the tags, ids, class names, attributes, types and much more to apply actions on them.

jQuery Selectors are of 4 types:

  1. ID Selector
  2. Class Selector
  3. Element Selector
  4. Universal Selector

jQuery selectors are based on the existing CSS selectors and which makes it to work with CSS easily.

Universal selector

Selects all element inside the document. This selects all elements in the HTML document including html, head and body. The symbol * is used to select the elements. Like any other jQuery selector, this selector also returns an array filled with the found elements.
$(“*”)


$(document).ready(function(){
   $("*").css("background-color","#D3D3D3");
});

Output:

Element selector

jQuery Element selector selects all elements with the specified type of element name in HTML document. Any number of selectors can be combined into a single result. Here DOM elements order in the jQuery object need not be identical.

$(“element”)

If here are multiple elements to be selected, use the character comma , to separate the elements.

$(“element_1,element_2,element_3”)


$(document).ready(function(){
    $("p").css("background-color","#D3D3D3");
});

Output:

#id selector

This jQuery id selector selects the elements in HTML document by its specified id. An id should be unique within a page, so #id selector looks for a single, unique element.

To find an element with a specific id, write a hash character, followed by the id of the HTML element:

$(“#id”)


$(document).ready(function(){
   $("#list").css("background-color","#D3D3D3");
});

Output:

.class selector

This jQuery class selector selects the elements in HTML document by its specified className. To identify the elements with a specific class, write a period character, followed by the name of the class:

$(“.class”)


$(document).ready(function(){
    $(".list").css("background-color","#D3D3D3");
});

Output:

Try your self 

Selecting Descendants

Descendants are the children,grandchildren etc of the designated ancestor element.This is used to select the descendants of the ancestor.

$(“ancestor descendant”)


$(document).ready(function(){
  $("table td").css("background-color","#D3D3D3");
});

Output:

Summary

  • jQuery Selectors select the required HTML elements.
  • This selection can be done based on elements,id or a class.