Understand the basic structure of the jQuery syntax.
Standard jQuery Syntax
A jQuery statement typically starts with the dollar sign ($) and ends with a semicolon (;).
In jQuery, the dollar sign ($) is just an alias for jQuery. Let’s consider the following example code which demonstrates the most basic statement of the jQuery.
Let’s discuss the code in the above example by understanding each part of this script individually.
The $(document).ready(handler); — This statement is commonly known as the ready event. The handler is basically a function that is passed to the ready() method to be executed safely as soon as the document is ready – when the DOM hierarchy has been fully constructed.
The jQuery ready() method is typically used with an anonymous function. So, the above example can also be written in a shorthand notation like this:
You can use any syntax you like as both the syntax are equivalent. However, the document ready event is easier to understand when reading the code.
Further, inside an event handler function you can write the jQuery statements to perform any action following the basic syntax, like: $(selector).action();
Where, the $(selector)
basically selects the HTML elements from the DOM tree so that it can be manipulated and the action()
applies some action on the selected elements such as changes the CSS property value, or sets the element’s contents, etc. Let’s consider another example that sets the paragraph text after the DOM is ready:
In the jQuery statement of the example above (line no-10) the p
is a jQuery selector which select all the paragraphs i.e. the <p>
elements in the document, later the text()
method set the paragraph’s text content to “Hello World!” text.
The paragraph text in the example above is replaced automatically when the document is ready. But what if we want the user to perform some action before executing the jQuery code to replace the paragraph text. Let’s consider one last example:
In the above example the paragraph text is replaced only when a click event is occur on the “Replace Text” <button>
that simply means when a user click this button.
Now that you have a basic understanding of how the jQuery works, in the upcoming chapters you will learn about the terms we’ve discussed here in detail.