In Lesson 3, we have learned how to use jQuery selectors based on name, id and class. In this lesson, we shall learn a few more example examples of jQuery selectors.
We use the symbol * in jQuery to select all elements. the syntax is as follows:
$("*")
<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ $("#btn1").click(function(){ $("*").hide(); }); }); </script> </head> <body> <button id="btn1">Click to hide All Elements</button><br> </body> </html>
Clicking the button below will hide everything on this page.
We use the keyword this to select the current element. The syntax is:
$(this)
<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ $("#btn2").click(function(){ $("this").hide(); }); }); </script> </head> <body> <button id="btn2">Hide Me</button> </body> </html>
we can select all elements with the same class name. The syntax is:
$("element.classname")
In this example, jQuery will select all p elements with class name "myclass"
<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ $("#btn3").click(function(){ $("p.myclass").hide(); }); }); </script> </head> <body> <h1 class="myclass">This is my heading</h1> <p class="myclass">This is paragraph 1 .</p> <p class="myclass">This is paragraph 2.</p> <button id="btn3">Click to hide paragraph</button> </body> </html>
This is paragraph 1 .
This is paragraph 2.
jQuery can select the first element out of the same elements found on the webpage. The syntax is:
$("element:first")
This example selects the first <h5> element and hides it.
<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ $("#btn4").click(function(){ $("h5:first").hide(); }); }); </script> </head> <body> <h5>First Topic</h5> <h5>Second Topic</h5> <h5>Third Topic</h5> </body> </html>
The syntax is
$("ul li:first")
<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ $("#btn5").click(function(){ $("ul li:first").hide(); }); }); </script> </head> <body> <h4>List of Fruits</h4> <ul> <li>Apple</li> <li>Banana</li> <li>Grape</li> <li>Orange</li> </ul> <p>List of Vegetables</p> <ul> <li>Broccoli</li> <li>Cabbage</li> <li>Celery</li> <li>Tomato</li> </ul> <button id="btn5">Strike off the first item</button> </body> </html>
List of Vegetables
There are many more variations of jQuery selectors and we shall deal with them in coming lessons.
Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy