jQuery Tutorial
jQuery Introduction jQuery Getting Started jQuery Syntax jQuery Selectors jQuery Events
jQuery Effects
jQuery Hide/Show jQuery Fade jQuery Slide jQuery Animation jQuery stop() jQuery Callback jQuery Chaining
jQuery Manipulation
jQuery Get/Set jQuery Add jQuery Remove jQuery CSS Classes jQuery css() jQuery Dimensions
jQuery Traversing
jQuery Traversing jQuery Ancestors jQuery Descendants jQuery Siblings jQuery Filtering
jQuery AJAX
jQuery AJAX Intro jQuery Load jQuery Get/Post jQuery AJAX Events
jQuery Misc
jQuery noConflict() jQuery Filters
jQuery References
jQuery Reference jQuery Selectors jQuery Events jQuery Effects jQuery HTML/CSS jQuery Traversing jQuery AJAX jQuery Miscellaneous jQuery Properties

jQuery Syntax

jQuery syntax is made by using HTML elements selector and perform some action on the elements.

jQuery basic syntax:

$(selector).action()
  • $ sign define the jQuery
  • (selector) used to find HTML elements
  • action() used to perform actions on the elements

Examples:

$(this).hide(): used to hide the current element

$("p").hide(): used to hide all <p> elements

$(".para").hide(): used to hide all elements with class="para"

$("#para").hide(): used to hide the element with id="para"

jQuery uses CSS syntax to select elements. You will learn more about the jQuery selectors in the next chapter.


The Document Ready Event

You might have noticed that all jQuery methods in our examples, are inside a document.ready event:

$(document).ready(function(){

  // jQuery Method (execute when DOM is ready)

});

This is to prevent any jQuery code from running before the document is finished loading.

It is good practice to wait for the document to be fully loaded and ready before working with it.

This also allows you to have JavaScript code before the body of your document, in the head section.

Here are some examples of actions that can fail if methods are run before the document is fully loaded:

  • Trying to select an element that is not created yet
  • Trying to get the size of an image that is not loaded yet

The jQuery also has an even shorter method for the document.ready event:

$(function(){

  // jQuery Method

});

The $(document).ready() is easier to understand when reading the code.

Note: The $(document).ready() is an event that is used to manipulate a page safely with the jQuery (code inside this event will only run once the DOM is ready).