jQuery Selectors
In the previous chapter we have learnt how jQuery works. In this tutorial we will be learning jQuery Selectors.
jQuery Selectors :
- CSS selectors are used to style the HTML elements.
- Similarly we can use jQuery to add behavior to the HTML element. jQuery Selectors are used to find or select HTML element.
- All selectors in jQuery start with the dollar sign and parentheses: $().
Different Ways of Using Selector are explained below -
1. Using Element as Selector
We can use HTML element as jQuery selector. It is most generalize way of using selector.
$("h1")
using above code we can select all h1 headings from the page -
<script> $(document).ready(function(){ $("button").click(function(){ $("h1").hide(); }); }); </script>
Using above code, we are hiding all the H1 heading from document after click event on any button.
2. Using Class as Selector
We can use jQuery selector to select HTML elements based on Class.
<!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $(".content").hide(); }); }); </script> </head> <body> <h2 class="content">Heading Data 1 </h2> <p class="content">Paragraph Data 1</p> <p>Paragraph Data 2</p> <button>Submit</button> </body> </html>