jQuery Syntax

In this guide, you will acquire the skills to compose jQuery code.


Standard jQuery Syntax

A jQuery statement typically commences with the dollar sign ($) and concludes with a semicolon (;). In jQuery, the dollar sign ($) serves as a shorthand alias for jQuery itself. Let's examine the following example code, illustrating the most fundamental jQuery statement.

<script>
$(document).ready(function () {
	// Some code to be executed...
	alert("Hello!");
});
</script>

The given example simply displays an alert message "Hello!" to the user.

Explanation of code

If you're new to jQuery, the code might seem a bit perplexing at first. Not to worry, let's dissect each part of this script step by step.

  • The <script> element: Since jQuery is essentially a JavaScript library, you can embed jQuery code within the <script> element. However, for best practices, it's advisable to place it in an external JavaScript file. In that case, you can simply omit this part.
  • The $(document).ready(handler): This line is commonly referred to as the ready event. Here, the handler is essentially a function passed to the ready() method, which is executed safely as soon as the document is fully prepared for manipulation. In other words, it runs when the DOM hierarchy has been completely constructed.

The jQuery ready() method is often used with an anonymous function. Hence, the previous example can also be expressed in a more concise notation like this:

<script>
$(function () {
    // Some code to be executed...
    alert("Happy Morning!");
});
</script>

Tip: You have the flexibility to use either syntax, as both are functionally equivalent. However, the document ready event syntax is generally more understand and straightforward when reading the code.


Accessing HTML Elements on ready() Event

Additionally, within an event handler function, you can compose jQuery statements to execute various actions using the fundamental syntax, such as: $(selector).action();

In this syntax, $(selector) effectively identifies HTML elements within the DOM tree for subsequent manipulation, while the action() method carries out specific actions on the selected elements. These actions can involve altering CSS property values, setting element contents, and more. Let's explore another example that modifies paragraph text once the DOM has completed loading:

<script>
$(document).ready(function () {
    $("p").text("Hello World!");
});
</script>

In the jQuery statement from the example above (line number 3), p serves as a jQuery selector that targets all paragraphs, i.e., the <p> elements, within the document. Later, the text() method is used to update the text content of the paragraph to display "Hello World!" text.


Accessing HTML Elements on click() Event

The paragraph text in the previous example is automatically replaced when the document is fully loaded. However, what if we wish to prompt the user to take some action before running the jQuery code to update the paragraph text. Let's see an example:

<script>
$(document).ready(function () {
    $("button").click(function () {
        $("p").text("Hello World!");
    });
});
</script>

In the previous example, the paragraph text undergoes replacement exclusively upon the occurrence of a click event on the "Replace Text" <button>. In other words, it changes when a user clicks this button.

Note: It's advisable to enclose your jQuery code within the document ready event to ensure that it runs when the document is fully prepared for manipulation.


FAQ

What is the basic syntax for a jQuery statement?

The basic syntax for a jQuery statement involves selecting HTML elements using a jQuery selector and then applying an action to those selected elements. It typically looks like this: $(selector).action();. The $(selector) portion selects the HTML elements, and the action() part performs an operation on those selected elements.

How do you use a jQuery selector?

jQuery selectors are used to identify and select HTML elements in the DOM (Document Object Model). You can specify the elements you want to select by using CSS-like syntax within the $() function. For example, to select all paragraphs, you can use $('p'). Selectors can be based on element names, IDs, classes, attributes, and more.

What is the purpose of the $(document).ready() function in jQuery syntax?

The $(document).ready() function, also known as the "document ready event," is used to ensure that your jQuery code executes only when the DOM has fully loaded and is ready for manipulation. It prevents code from running before the HTML document is fully parsed. It's a best practice to wrap your jQuery code inside this function to ensure it works as intended.

How can you apply CSS styles to selected elements using jQuery?

To apply CSS styles to selected elements in jQuery, you can use the .css() method. Here's an example:

$('selector').css('property', 'value');

Replace 'selector' with the element you want to target, 'property' with the CSS property you want to set, and 'value' with the desired value for that property.

What are jQuery event handlers, and how do you use them?

jQuery event handlers are functions that respond to specific events, such as a click, hover, or keypress event. You can attach event handlers to selected elements using methods like .click(), .hover(), or .on(). Here's an example of attaching a click event handler:

$('button').click(function() {
    // Code to execute when the button is clicked
});

The function inside .click() is the event handler, where you define the actions to perform when the event occurs.

How do you manipulate the content of an HTML element using jQuery?

jQuery provides several methods to manipulate the content of HTML elements. One common method is .text(), which sets or retrieves the text content of an element:

// Set the text content of a paragraph
$("p").text("Hello, jQuery!");

// Get the text content of a paragraph
var text = $("p").text();

Similarly, .html() can be used to manipulate the HTML content of elements:

// Set the HTML content of a div
$("div").html("<strong>Formatted text</strong>");

// Get the HTML content of a div
var htmlContent = $("div").html();

How do you handle events using jQuery?

jQuery simplifies event handling by providing the .on() method. This method allows you to attach event handlers to selected elements. For example, to handle a click event on a button:

$("button").on("click", function() {
  // Code to execute when the button is clicked
});

You can also delegate events for dynamically added elements using the .on() method:

$(document).on("click", "button", function() {
  // Code to execute when any button, present or future, is clicked
});