jQuery syntax follows a simple and easy to remember structure to select and manipulate the HTML elements. It uses the CSS selectors such as class name, div id, element names etc. to select the HTML elements and perform the actions on it. The basic syntax is shown below.
$(selector).action();
jQuery Syntax Structure
- The $ symbol defines that the code is written in jQuery. Actually it is a syntactic sugar which is a shorthand for jquery. Writing jquery instead of $ is also acceptable as shown below.
jquery(selector).action();
- (selector) section is where the CSS selectors are specified to select the HTML elements. The CSS selectors such as id, class, element name etc. can be used to select the required HTML element. A sample is shown below.
$("#header").action();
In the above example, the action will be performed on an HTML element that has the CSS id as ‘header’.
- The final part which is the action() section is the one that performs the specified action on the selected HTML elements.
$("#header").hide();
In the above example, the hide() action will hide the HTML element which has the id ‘header’.
$(document).ready() function
The $(document).ready() function in jQuery identifies the readiness of a HTML document to be manipulated. It is not safe to to perform any JavaScript actions on a document that has not loaded completely. The syntax is shown below with an example.
$(document).ready(function () { $("#header").hide(); });
In the above example, the HTML element with the id ‘header’ will be hidden one the document has loaded successfully. The $(document).ready() function helps to perform the jQuery actions only after the DOM has loaded successfully.