jQuery Syntax
With jQuery, you can select (query) HTML elements and perform "actions" on them.
jQuery Syntax
The jQuery syntax is based on selecting HTML elements and performing actions on the selected elements.
Basic syntax:$(selector).action()
- The dollar sign defines jQuery
- The selector "queries" and "finds" HTML elements
- jQuery's action() performs an operation on the elements
Example:
-
$(this).hide() - hides the current element
-
$("p").hide() - hides all <p> elements
-
$("p.test").hide() - hides all <p> elements with class="test"
-
$("#test").hide() - hides the element with id="test"
|
Are you familiar with CSS selectors? The syntax used by jQuery is a combination of XPath and CSS selector syntax. In the following chapters of this tutorial, you will learn more about selector syntax. |
Document Ready Event
You may have noticed that all jQuery functions in our example are inside a document ready function:
This is to prevent jQuery code from running before the document is fully loaded (ready), i.e., operations on the DOM can only be performed after the DOM has finished loading.
If functions run before the document is fully loaded, the operations may fail. Here are two specific examples:
- Trying to hide an element that does not exist
- Getting the size of an image that is not fully loaded
Tip:Shorthand syntax (same effect as above):
You can choose either of the above two methods to execute jQuery methods after the document is ready.
Other Extensions