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:
- $(document).ready(function(){
-
- });
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.
- <html>
-
- <head>
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
- </head>
-
- <body>
- <div id="demo"></div>
- <script type="text/javascript">
- $(document).ready(function() {
- $("#demo").html("Hey jQuery is working");
- });
- </script>
- </body>
-
- </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.