The jQuery syntax is specifically designed to make selecting and interacting with HTML elements extremely fast.
The standard syntax follows a simple pattern: find an element, then do something with it.
The basic syntax looks like this: $(selector).action()
Let's break down what each part means:
$ sign is used to define and access jQuery. It is an alias for the word "jQuery".(selector) is used to find specific HTML elements (like paragraphs, buttons, or divs).action() is the jQuery function to be performed on the selected elements (like hiding or fading).Here are some common examples of how you select and manipulate elements:
$(this).hide() — Hides the current element being interacted with.$("p").hide() — Hides every single <p> (paragraph) element on the page.$(".test").hide() — Hides all elements that have the CSS class class="test".$("#test").hide() — Hides the one specific element with id="test".You might notice that almost all jQuery code is placed inside a "Document Ready" event block.
This is a crucial concept to understand for good web performance and bug-free code.
$(document).ready(function(){
// All jQuery methods go here...
$("p").hide();
});
The ready event ensures that your jQuery code does not run before the HTML document is fully loaded.
If your code runs too early, you might try to select elements that don't exist yet!
Here are examples of what goes wrong if you don't wait:
Because the Document Ready event is used so often, jQuery provides a shorter, quicker way to write it.
Instead of writing $(document).ready(function(){ ... }), you can just write:
$(function(){
// All jQuery methods go here...
$("p").hide();
});
Both methods do the exact same thing, but the shorthand version saves you time!
Search engine crawlers (like Googlebot) are capable of executing JavaScript.
Using the Document Ready event ensures that crawlers see your final, manipulated DOM structure properly.
Which symbol is universally used as an alias for jQuery?
Why do we use the $(document).ready() event?