Syntax of jQuery

The jQuery syntax is designed specifically for selecting HTML elements and performing actions on them (s).

The fundamental syntax is: $ (selector).action()

  • To define/access, use a $ sign. To "query (or find)" HTML elements, use jQuery A (selector).
  • A jQuery action() that will be applied to the element (s)

Examples:

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

 


Do you know what CSS selectors are?

To select elements, jQuery employs CSS syntax. In the following chapter of this tutorial, you will learn more about the selector syntax.

If you don't know CSS, check out our CSS Tutorial.


The Document Preparedness Activity

You might just have noticed that almost all of the jQuery methodology in our illustrations are contained within a document ready Activity :

$(document).ready(function(){

  // jQuery methods go here...

});

This is done to prevent any jQuery code from running before the document has completed attempting to load (is ready).

It is preferable to wait until the document has been fully loaded and is ready before working with it. This also entails placing your JavaScript code in the head section of your document, before the body.

Here are some actions that may fail if methods are named before the document has fully loaded:

Attempting to conceal an element that has yet to be created Trying to calculate the size of an image that hasn't yet been loaded

Hint: The same jQuery group has also developed a more concise procedure for the document ready event:

$(function(){

  // jQuery methods go here...

});

EXAMPLE ❯


Use your ideal syntax. When reciting the code, we presume that the document ready event is easier to understand.