Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

jQuery syntax


May 07, 2021 jQuery


Table of contents


jQuery syntax


With jQuery, you can pick (query, query) HTML elements and "action" them.


jQuery syntax

The jQuery syntax is done by picking HTML elements and performing certain actions on the selected elements.

Basic syntax: $ ( selector ) action ()

  • The dollar sign defines jQuery
  • Selector "query" and "find" HTML elements
  • jQuery's action() performs an action on the element

Instance:

$(this.hide) - Hide the current element

$("p").hide() - Hide all paragraphs

$("p .test").hide() - Hide all the paragraphs of class="test"

$("#test").hide() - Hide all the elements of id"test"

jQuery syntax Are you familiar with the CSS selector?

The syntax used by jQuery is a combination of XPath and CSS selector syntax. In the next sections of this tutorial, you'll learn more about the syntax of selectors.


Document-ready events

You may have noticed that all the jQuery functions in our instance are in a document ready function:

$(document).ready(function(){

// Start writing jQuery code ...

});

This is to prevent the document from running jQuery code before it is fully loaded (ready).

If you run a function before the document is fully loaded, the operation may fail. Here are two specific examples:

  • An attempt was made to hide an element that did not exist
  • Gets the size of the image that is not fully loaded

Tip: Simple writing (same as above):

$(function(){

// Start writing jQuery code ...

});

There are two ways you can choose the way you like to implement the jQuery method when the document is ready.