jQuery Syntax

jQuery Syntax

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 Structure

The basic syntax looks like this: $(selector).action()

Let's break down what each part means:


Examples of jQuery Syntax

Here are some common examples of how you select and manipulate elements:


The Document Ready Event

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.

The Document Ready Method:

$(document).ready(function(){

// All jQuery methods go here... $("p").hide();

});


Why Wait for the Document to be Ready?

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:


The Shorthand Document Ready

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:

Shorthand Ready Method:

$(function(){

// All jQuery methods go here... $("p").hide();

});

Both methods do the exact same thing, but the shorthand version saves you time!


Ensuring SEO Friendly Execution

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.


Exercise 1 of 2

?

Which symbol is universally used as an alias for jQuery?

Exercise 2 of 2

?

Why do we use the $(document).ready() event?