Syntax of jQuery

Explore different syntactical elements of jQuery such as $, (selector), action(), and $(document).ready().

The syntax of jQuery allows easy selection and modification of elements on a web page. The three most important syntactical elements of jQuery are:

  • $
  • (selector)
  • action()

The resulting jQuery statement formed by the combination of these elements is:

Let’s discuss each of these syntactical elements in detail.

Why the $?

The $ function returns a collection of matched elements from the DOM, based on the passed arguments. The $ function is a shorter representation of the library’s jQuery() function.

Both jQuery("p") and $("p") select and return the same list of elements i.e. all paragraph elements present in the web page. We can see this in the example below.

Console

The use of $ instead of jQuery() makes the code cleaner and shorter.

Selectors and actions

Selectors extract the HTML elements present on a web page by using different patterns. Actions on the other hand, are effects and events, performed on the extracted HTML elements.

For example, in the code below, 'li', #show and '#hide' are selectors, while click(), hide() and show() are actions:

$(document).ready()

The Document Object Model (DOM) is an object tree created by a browser when a page loads. All elements of the page are stored in a hierarchical fashion within this tree.

jQuery deals with DOM manipulation, traversal, selection, and more. The document must be entirely loaded and ready before we start manipulating and traversing with jQuery. All of the jQuery code is placed inside the $(document).ready() function, to ensure that its execution takes place safely, after the entire document is loaded.

In the code snippet below, we want to append the text “This is a paragraph” to the p element, only after the document is ready. So, we placed all the jQuery code inside the document ready function.