We use jQuery selectors to identify, select and manipulate the elements of the HTML document. Using jQuery selectors we can identify an element with its ID and class. Once we identify the element(s) we want, we can read the element’s attributes along with attribute values, apply style sheets, hide or show element content based on conditions and much other functionality. Please subscribe to our future articles here.
- Buy : jQuery in Action
Fundamentally, let’s discuss about three types of jQuery selectors most commonly used.
- ID selector
- Class selector
- Element selector
ID selector
The ID selector is used to identify a specific element by the element’s ID attribute. We use ID selector to particularly identify a single unique element of a page. The following example finds a div element with ID dataDiv.
$("#dataDiv")
Once we found the div element we needed, we can make changes to the element. The following example adds a border to the div element we just found in the above example.
$("#dataDiv").css("border", "5px solid green");
Class selector
The class selector is used to identify a single element or a set of elements in a page with common class attribute. We may get more than one element when we use class selectors. The following example finds an element with class dataClass.
$(".dataClass")
Here is the element with its class attribute.
<div class="dataClass">…</div>
In the above example, since we have only one div element with class dataClass, we only get one element. However, if we have more than one div element with same class we may get multiple elements. For instance, the following example has more than one div elements with same class and we use class selectors to get all the elements.
<div id="dataDiv1" class="dataClass">…</div> <div id="dataDiv2" class="dataClass">…</div> <div id="dataDiv3" class="dataClass">…</div> <div id="dataDiv4" class="dataClass">…</div>
The jQuery code will returns four elements.
$(".dataClass")
In order to iterate over four of div elements we get, we use each construct.
$(".dataClass").each(function(index) { alert($(this).text() + " : " + index); });
In the above code snippet, we are iterating over the div elements and displaying their index and contents. Notice that for each iteration in the loop, the $(this) refers to the current element. The function text() displays the contents of the element.
Element selector
We use jQuery element selectors to select elements based on their tag names. The following example gets all heading 1 tags (H1).
$("h1")
Once we have the elements we can manipulate them. The following example hides all the heading 1 tags.
$("h1").hide();
jQuery selectors are flexible, programmer friendly and great way to locate elements in the HTML pages. We can use jQuery selectors for formatting, hiding or showing content conditionally, appending the element to another element and much more.
- Buy : jQuery in Action