Monday, July 1, 2013

Selector in JQuery

JQuery Selectors are one of the most important part of a Jquery statement. They allow us to select particular element from the web page and perform some kind of action on them. This selection may be based on CSS selectors or based on their own custom selectors.

All the selectors are represented by $ followed by parenthesis, $().




The element Selector:

The element selector is that which selects the elements based on the element name. For example, if we write $("p"), it represents to select all the elements in the <p> tag and perform some kind of action on them.

Example:

  1. <html>
  2. <head>
  3. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
  4. </script>
  5. <script>
  6. $(document).ready(function(){
  7.   $("button").click(function(){
  8.     $("p").hide();
  9.   });
  10. });
  11. </script>
  12. </head>

  13. <body>
  14. <h2>This is a heading</h2>
  15. <p>This is a paragraph.</p>
  16. <p>This is another paragraph.</p>
  17. <button>Click me</button>
  18. </body>
  19. </html>
Try the above example to know how the element selector works.

Along with the element selector, we can also use the CSS selectors such as id, classes and also even with the  attributes, values of the attributes. 

The #id Selector:

For the #id selector, we are going to use the selector to be as
$("#id_name")

The .class Selector:

For the .class selector, we use the following format, 
$(".class")
There are many more ways of using selectors, which you can find by checking the JQuery Selectors Reference.