Advertisement

Google Ad Slot: content-top

Basic jQuery Syntax


With jQuery, you select HTML elements and perform actions on them. The basic syntax is:



$(selector).action();


  • $ → Refers to jQuery.
  • selector → Finds (or queries) the HTML element(s).
  • action() → The jQuery method that performs an action on the element(s).


Examples:


  • $(this).hide() - Hides the current element (the one that triggered the event)
  • $("p").hide() - Hides all <p> (paragraph) elements on the page
  • $(".test").hide() - Hides all elements with class="test"
  • $("#test").hide() - Hides the element with ID="test"


Note

jQuery selectors are based on CSS selector syntax. So if you're familiar with CSS, you're already familiar with jQuery selectors.

💡 Tip: If you're new to CSS, check out a CSS Tutorial first for a better understanding.

The Document Ready Event

Before you run any jQuery code, make sure the HTML document is fully loaded.

$(document).ready(function() {
// jQuery code goes here
});

To prevent jQuery code from running too early — before the HTML document is fully loaded.


If your script tries to interact with elements that don’t exist yet (because the browser hasn’t finished loading them), you'll get errors or unexpected behavior.


Shorter Version:

$(function() {
// jQuery code goes here
});