jQuery Syntax
With jQuery, you can select (query) HTML elements and perform "actions" on them.
jQuery Syntax
The jQuery syntax is designed to select HTML elements and perform some actions on the selected elements.
Basic syntax: $(
- The dollar sign defines jQuery
- The selector "queries" and "finds" HTML elements
- jQuery's action() performs actions on the elements
Examples:
- $(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? <br> <br>jQuery uses a combination of XPath and CSS selector syntax. In the next sections of this tutorial, you will learn more about selector syntax. | | --- | --- |
Document Ready Event
You may have noticed that all jQuery functions in our examples are inside a document ready function:
$(document).ready(function(){
// Start writing jQuery code...
});
This is to prevent any jQuery code from running before the document is finished loading (ready), meaning the DOM must be fully loaded before any DOM manipulation can occur.
Running functions before the document is fully loaded can lead to failures. Here are two specific examples:
- Attempting to hide a non-existent element
- Getting the size of an image that hasn't fully loaded
Tip: Concise write-up (same effect):
$(function(){
// Start writing jQuery code...
});
You can choose either method you prefer to execute jQuery methods after the document is ready.