Selectors in jQuery


jQuery Selectors are used to select HTML elements. There are many types of selectors in jQuery. such as element name, Id, Classes and more.

Tag Selector:

The Tag Selector used to Select all elements of given element name. For Example $("h1") select all h1 elements in the document.The following example shows, how to change text colour of all <p> elements in the document.

Example
<html>
  <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
  <body>
    <p>Hello World</p>
    <p>Sample Text</p>
    <p>Sample Paragraph</p>
  </body>
  <script>
    $(document).ready(function(){
      $("p").css({"color":"red"});
    });
  </script>
</html>
Try it Yourself

id Selector:

The id selector used to select single element with a specific id. For Example $("#para") select single id='para' element in the document. The following example shows, how to change text colour of element with id='para'.

Example
<html>
  <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
  <body>
    <p>Hello World</p>
    <p id='para'>Sample Text</p>
    <p>Sample Paragraph</p>
  </body>
  <script>
    $(document).ready(function(){
      $("#para").css({"color":"red"});
    });
  </script>
</html>
Try it Yourself

class Selector:

The class selector used to select multiple elements with a specific class name. For Example $(".cls") select all id='txt' elements in the document with class='cls'. The following example shows, how to change text colour of multiple elements with class='.cls'.

Example
<html>
  <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
  <body>
    <p class='cls'>Hello World</p>
    <p>Sample Text</p>
    <p class='cls'>Sample Paragraph</p>
  </body>
  <script>
    $(document).ready(function(){
      $(".cls").css({"color":"red"});
    });
  </script>
</html>
Try it Yourself

More Selectors

Syntax Description
$("*")
select all elements.
$("this")
select the current element.
$("tr:odd")
select all odd <tr> elements.
$("tr:even")
select all even <tr> elements.
$("tr:first")
select the first <tr> elements.
$("tr:last")
select the last <tr> elements.
$("tr:eq(n)")
select the (n)th index of selected <tr> elements.
$("tr:lt(n)")
select all <tr> elements below (n)th index.
$("tr:gt(n)")
select all <tr> elements above (n)th index.
$("tr:not(.cls)")
select all <tr> elements except class='cls'.
$(":text")
select all text input elements.
$(":password")
select all password input elements.
$("p:[align='right']")
elect all <p> elements with align='right'