jQuery Syntax

jQuery is all about playing around with HTML. If you don't know what jQuery is and how to use it, I will recommend you read jQuery Library.

The syntax of jQuery is very simple and easy to remember. You just need to remember $(selector).action()
Now, let's see, what is $(selector).action().
  • "$" is jQuery selector function. As in JavaScript, you would have noticed getElementById(), the same task is performed by $ in jQuery.
  • "Selector" is any HTML Id, class or element which you want to select.
  • "Action" is the action to be performed on the selector.
Having understood this, let's move to the most important event in jQuery, shown below:
  1. $(document).ready(function(){  
  2.  //jQuery code here  
  3. });  
What does this $(document).ready(function(){}); does?

As seen above, $ is the selector function. Here, document is the selector. This means, we want to select the document. Thus, ready() is the action to be performed on the document. ready() action checks whether HTML document is ready (fully loaded) or not. Only when HTML document will be loaded, will we be able to manipulate it, right?

Hence, to play around with HTML, we need to load it first. Once the document is ready, we perform the other activities. We write all jQuery methods inside this $(document).ready() block.

Now, let us understand the syntax with the help of demo example.
  1. <html>  
  2.   
  3. <head>  
  4.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>  
  5. </head>  
  6.   
  7. <body>  
  8.     <div id="demo"></div>  
  9.     <script type="text/javascript">  
  10.         $(document).ready(function() {  
  11.             $("#demo").html("Hey jQuery is working");  
  12.         });  
  13.     </script>  
  14. </body>  
  15.   
  16. </html>  
In this example, I have created a division with id="demo". The division does not have anything in it. Inside the document ready function, you can see that we are selecting the Id demo with the help of #, i.e. in the similar way, as we do in css. In the action, we have .html()

.html() is similar to the innerHTML property. In simple words, it replaces the empty division, which we created with the content written in it. Thus, we will get "Hey jQuery is working", when we see the output.

In the demo example, I have used Id selector along with html() action. Try to use class and element selectors. Only when you practice, will you understand it better. I hope this article was useful.
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now