03- jQuery Selectors

Introduction

jQuery library offers a wide range of selectors so that you can easily select the required HTML elements to apply actions on them. jQuery allows you to select elements using their tags, ids, class names, attributes, types and much more. If you are familiar with CSS selectors, you will find it very easy to deal with CSS selectors as jQuery selectors are based on the existing CSS selectors.

All jQuery selectors should start with $ (dollar) sign and the selector should be specified within parentheses: $(selector)

Different Selectors

I am going to explain different selectors with code samples. Make sure that the latest version of jQuery saved as jquery.js and the .html file that contains the sample code reside in the same folder.

Sample Code that illustrates the First Few Examples:

<html>
  <head>
   <title>Sample Code</title>
   <style>
    div
    {
     width:100px;
     height:100px;
     border:1px solid black;
     background-color:pink;
    }
   </style>
   <script src="jquery.js"></script>
   <script>
    //here we will add the code as we explain different selectors
   </script>
  </head>
  <body>
      <button>Click Me!!!</button><br />
      <div id="first" class="divs">First Box</div><br />
      <div id="second" class="info">Second Box</div><br />
      <div id="third" class="divs">Third Box</div>
      <p class="info">First Paragraph</p>
      <p class="divs">Second Paragraph</p>
      <p class="info">Third Paragraph</p>
  </body>
</html>

Copy the above lines of code and paste in a new file. Save the file as index.html. Make sure that index.html file and the jQuery file saved as jquery.js reside in the same folder. If you are not changing the name of the jQuery file downloaded, the src attribute of the script element (here it is jquery.js) should be changed accordingly.

1. $("*") à This will select all the elements on a page.

Add the following lines of code inside the <script> section. Open the file using your browser after saving the changes.

$(document).ready(function() {
    $("button").click(function(){
            $("*").hide();
       });
 });

Here we have selected all the elements to apply the hide effect.

2. $("div")  à This will select all the <div> elements on a page.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("div").fadeToggle("slow");
       });
  });

Here we have selected the <button> element as well the <div> elements using their tag. On the click of the button, the fadeToggle effect is applied to all <div> elements

3. $("#second")  à This will only the element with id=second on a page. Note that we need to use the # (hash) symbol to select elements using ids.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("#second").fadeToggle("slow");
            });
  });

Here, we have selected only the box with id=second to apply the fadeToggle effect.

4. $(".divs")  à This will select all the elements with class=divs on a page. Note that we need to use the . (dot) symbol to select elements using class.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $(".divs").fadeToggle("slow");
      });
});

You could find that even <div> elements and <p> element with class=divs are selected using this selector.

5. $(this)  à This will select the current element on a page.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $(this).hide();
      });
});

Here only the button is hidden as it is the current element.

6. $("#first, .info")  à This will select the element with id=first and element(s) with class=info on a page. Note that you can have more than one selector separated by comma.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("#first, .info").fadeToggle("slow");
      });
});

Here the first box (with id first) and second box, first and third paragraphs (with class info) are selected.

7. $("p:first")  à This will select the first <p> element. Note that it does not have any relationship with the id or class name. Among all <p> elements, the first <p> element will be selected.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("p:first").hide();
      });
});

Here the first <p> element is selected.

8. $("div:last")  à This will select the last <div> element.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("div:last").hide();
      });
});

Here the third <div> element is selected as it is the last <div> element.

9. $("p.info")  à This will select all <p> elements with class=info.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("p.info").hide();
      });
});

Here the first and third <p> elements are selected.

10. $("p:not(.info)")  à This will select all <p> elements except those with class=info.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $(""p:not(.info)").hide();
      });
});

Here the first and third <p> elements are selected.

Sample Code that illustrates the Next Few Examples:

<html>
  <head>
   <title>Sample Code</title>
   <script src="jquery.js"></script>
   <script>
   </script>
  </head>
  <body>
    <button>Click Me!!!</button><br />
    <p>First List</p>
          <ul>
             <li>Aaron</li>
             <li>Abel</li>
             <li>Hannah</li>
             <li>Sarah</li>
          </ul>
          <p>Second List</p>
          <ul>
             <li>Maths</li>
             <li>Science</li>
             <li>English</li>
          </ul>
  </body>
</html>
  1. $("li:even") à This will select all the even <li> elements on a page. Note that the index starts from 0 and not from 1.

Add the following lines of code inside the <script> section. Open the file using your browser after saving the changes.

$(document).ready(function() {
    $("button").click(function(){
            $("li:even").hide();
    });
});

Here Aaron (index=0) and Hannah (index=2) from the first list and Maths (index=0) and English (index=2) from the second list will be hidden.

  1. $("ul:last li:odd") à This will select all the odd <li> elements from the last <ul> element on a page.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("p.info").hide();
      });
});

Here, Science (index=1) from the last list will be hidden.

  1. $("li:gt(1)") à This will select all the <li> elements with index greater than one (index starts from 0).

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("ul:first li:gt(1)").css("background-color", "yellow");
    });
});

Here, Hannah and Sarah from the first list will be selected as their indexes are 2 and 3.

  1. $("li:eq(1)") à This will select the <li> element with index equal to one.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("ul:first li:eq(1)").css("background-color", "yellow");
    });
});

Here, Abel will be selected that has index equal to on1.

  1. $("li:lt(1)") à This will select all the <li> elements with index less than one.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("ul:first li:lt(1)").css("background-color", "yellow");
    });
});

Sample Code that illustrates the Next Few Examples:

<html>
  <head>
   <title>Sample Code</title>
   <script src="jquery.js"></script>
   <script>
   </script>
  </head>
  <body>
      <p>First Paragraph</p>
      <div>
          <p>First Div: First Paragraph</p>
          <span>First Div: First Span</span>
          <p>First Div: Second Paragraph</p>
      </div><br />
      <div>
          <span>Second Div: First Span</span>
          <p>Second Div: <span>First</span> Paragraph</p><span>Second Div: Second Span</span>
      </div>
      <button>Click Me!!!</button><br />
   </body>
</html>
  1. $("p:first-child") à This will select all the <p> elements that are the first child of their parents.

Add the following lines of code inside the <script> section. Open the file using your browser after saving the changes.

$(document).ready(function() {
    $("button").click(function(){
            $("p:first-child").hide();
    });
});

Note that it also selects the first <p> element as it is the first child of the <body> element.

  1. $("span:last-child") à This will select all the odd <span> elements that are the last child of their parents.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("span:last-child").hide();
    });
});
  1. $("p:first-of-type") à This will select all the <p> elements that are the first <p> element of their parents.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("p:first-of-type").hide();
    });
});
  1. $("p:nth-child(2)") à This will select all the <p> elements that are the second child of their parents.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("p:nth-child(2)").hide();
    });
});

Here, the "Second Div: First Paragraph" element will be selected as it is the second child of its parent.

  1. $("p:nth-of-type(2)") à This will select all the <p> elements that are the second <p> element of their parents.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("p:nth-of-type(2)"). css("background-color", "red");
    });
});

Here, the "First Div: Second Paragraph" element will be selected as it is the second <p> element of its parent.

  1. $("span:only-child") à This will select all the <span> elements that are the only child of their parents.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("span:only-child").hide();
    });
});

Here, none of the elements will be selected as there is no <span> element that is the only child of its parent.

  1. $("div > span") à This will select all the <span> elements that are the direct child of a <div> element.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("div > span").css("background-color", "red");
    });
});

Note that the First in the "Second Div: First Paragraph" is not selected as it is not the direct child of <div> element.

  1. $("div span") à This will select all the <span> elements that are the direct or indirect child of a <div> element.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("div span").css("background-color", "red");
    });
});

Note that the First in the "Second Div: First Paragraph" is also selected here.

  1. $("p + span") à This will select all the <span> elements that are after a <p> element.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("p + span").css("background-color", "red");
    });
});

Note that the "Second Div: First Span" is not selected as it is not after a <p> element.

  1. $("span ~ p") à This will select all the <p> elements that are siblings of a <span> element.

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("span ~ p").css("background-color", "red");
    });
});

Sample Code that illustrates the Next Few Examples:

<html>
  <head>
   <title>Sample Code</title>
   <style>
   </style>
   <script src="jquery.js"></script>
   <script>
   </script>
  </head>
  <body>
      <button>Click Me!!!</button><br />
       <p id="first">First Paragraph</p>
       <p id="second">Second Paragraph</p>
       <p id="fourth">Fourth Paragraph</p>
       <p id="fifth">Fifth Paragraph</p>     
  </body>
</html>
  1. $("[id='first']") à This will select the element with id=first.

Add the following lines of code inside the <script> section. Open the file using your browser after saving the changes.

$(document).ready(function() {
    $("button").click(function(){
            $("[id='first']").css("background-color","yellow");
       });
 });
  1. $("[id^='fi']") à This will select all the elements with id that starts with "fi".

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("[id^='fi']").css("background-color","yellow");
       });
 });

Here the first and fifth paragraphs will be selected.

  1. $("[id$='th']") à This will select all the elements with id that ends with "th".

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("[id$='th']").css("background-color","yellow");
       });
 });
  1. $("[id*='o']") à This will select all the elements with id that contains the character "o".

Clear the code inside the <script> section and add the following lines of code.

$(document).ready(function() {
    $("button").click(function(){
            $("[id*='o']").css("background-color","yellow");
       });
 });

Here the second and fourth paragraphs will be selected.

Summary

In this section, we have seen many different types of selectors to select the HTML elements. In addition to these, there are many more selectors and you can find information about these selectors in the official website of jQuery.

Like us on Facebook