The basic function of jQuery is to select some HTML elements from a webpage and perform some actions on them. This will update the content of the web page.
The jQuery syntax is as follows:
$(selector).action()
A $ sign to define/access jQuery A (selector) to "query (or find)" HTML elements A jQuery action() to be performed on the elements.
action is actually a jQuery method. There are numerous jQuery methods. The following examples use the hide method to hide selected elements.
Examples:
$(this).hide() // hides the current element. $("p").hide() //hides all <p> elements. $(".abc").hide() // hides all elements with class="abc". $("#abc").hide() // hides the element with id="abc".
You must place the jQuery JavaScript in the <head> section of the webpage, as follows:
<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ // jQuery code...... }); </script> </head>
An alternative method is to create a jQuery JavaScript file and link it to the web page. For example, you have created a jQuery JavaScript file jqry.js. Link this file using the syntax as follows and place it within the <body> section of the webpage:
<script src="jQuery/jqry.js"></script>
In this example, we use the jQuery 'hide' method to hide the h1 element.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("h1").hide(); }); }); <script> </head> <body> <h1>This is heading1</h1> </body> </html>
You can hide more than one element at one go by adding another hide method to the first method, separated by a ;.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").hide();$("h2").hide(); }); }); <script> </head> <body> <h2>This is the title</h2> <p>This is the paragraph</p> <button>Click me to hide title and paragraph</button> </body> </html>
This is the paragraph
Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy