In this article I will discuss the various ways by which we can select an element in HTML page using Jquery. If you want to know how to start Jquery development you can read this article. After setting up the project and environment we can start our development with Jquery selectors.
What are Jquery selectors?
- Selectors allow the developer to select the page elements and help to work on the element by creating an Jquery wrapper object for the element.
- Single or multiple elements can be selected.
- A Jquery object can be created by using $(selector) or jquery(selector) syntax. I will use the $() in the article
Tag Name Selector
An HTML element can be selected by the tag name which is the element itself. Check the below examples.
$('p') Selects all the paragraph $('li') Selects all the list item $('a') Selects all the anchors $('p, li, a') Selects all the three elements present in the page
To Select the multiple tags we can use the comma (,) to separate the elements. Please check the last line in the previous example.
Descendant Selector
Descendant are the children, grandchildren of the designated element.
$('ol li') - Selects all the list item which are descendant of the ordered list $('table tr') - Selects all the row item of the table element
ID Selector
Use the hash ‘#’ character to select element by id
$('#outputTable') - Selects the table named outputTable from the below code
ID | First Name | Last Name |
Class Jquery Selectors
Use the dot ‘.’ character to select the elements by their class names. We can also select multiple tags by separating the class names by ‘,’ comma character. Examples are below.
$('.myClass') - Selects all the tags with 'myClass' $('.topDiv, .bottomDiv') - Selects all the tags containing topDiv and bottomDiv class $('a.myClass') - Combine the class with element names. This will select all the tags in 'myClass'
Attribute Value Jauery Selectors
We can select the tags based on the attribute name and attribute value.
$('a[title]') - Selects all the elements which have title attribute $('a[title="Jquery Programming"]') - Selects all the elements which have a title as "Jquery Programming"
Input element selectors
To select all the input elements including input, select, textarea, button, image, radio button we can use $(‘:input’) selector.
$(':input[type="radio"]') - Selects all the radio button on page
Using Contains in Selectors
Select the elements which matches the contents of the elements within the “contains”
$('div:contains("dot net")') - Selects the div that contain the text "dotnet" as content. The match is case sensitivedot net for all
Odd Even Selectors
$(‘tr:odd’) and $(‘tr:even’) is the Jquery selector for selecting the odd or even rows . The index is zero based.
Selecting the First Child
$(‘element:first-child’) – Selects the first child of every element group.
$('span:first-child')This is selectedThis is selected
Leave a Reply