Home Videos Exercises MCQ Q&A Quiz E-Store Services Blog Sign in Appointment Payment

jQuery Syntax

With jQuery you select (query) HTML elements and perform "actions" on them.


jQuery Syntax

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s).

Basic Syntax is: $(selector).action()

  • A $ sign to define/access jQuery
  • A (selector) to "query (or find)" HTML elements
  • A jQuery action() to be performed on the element(s)

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


The document ready event

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

Example: $(document).ready(function(){ });

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

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 your 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 hide an element that is not created yet
  • Trying to get the size of an image that is not loaded yet

Select element and change content

$("#myId").text("New text here"); // Select by ID
$(".myClass").html("Bold text"); // Select by class
$("p").hide();


Click event

$("#btn").click(function(){ alert("Button clicked!"); });


CSS Manipulation

$("h1").css("color", "red");


Hide/Show Elements

$("#box").hide(); // Hides the element
$("#box").show(); // Shows the element
$("#box").toggle(); // Toggles visibility


Ajax example

$.get("data.txt", function(data){ $("#output").html(data); });