Syntax in Jquery
? jQuery Syntax
The basic syntax of jQuery is designed to be simple and readable. It follows this pattern:
? Basic Syntax
$(selector).action();| Part | Description |
|---|---|
$ | Accesses the jQuery library |
selector | Selects HTML elements (just like in CSS) |
action() | A jQuery method (like .hide(), .click(), .css(), etc.) that does something |
? Example Syntaxes
? Select and hide a paragraph:
$("p").hide();Hides all
<p>elements.
? Change the color of elements with class .box:
$(".box").css("color", "red");? Attach a click event to a button:
$("#myButton").click(function(){ alert("Button clicked!");});? Chain multiple actions:
$("#title").css("color", "blue").slideUp(2000).slideDown(2000);? Common jQuery Actions
| Method | Description |
|---|---|
.hide() | Hides the selected elements |
.show() | Shows hidden elements |
.toggle() | Toggles visibility |
.css() | Changes or gets CSS styles |
.html() | Gets or sets HTML content |
.text() | Gets or sets text content |
.attr() | Gets or sets attributes |
.val() | Gets or sets form values |
.addClass() | Adds a class |
.removeClass() | Removes a class |
? Document Ready Syntax
This ensures the DOM is fully loaded before running jQuery code:
$(document).ready(function(){ // jQuery code here});Or the shorthand version:
$(function(){ // jQuery code here});? Full Example:
<!DOCTYPE html><html><head> <title>jQuery Example</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function(){ $("#hideBtn").click(function(){ $("p").hide(); }); }); </script></head><body> <p>This is a paragraph.</p> <button id="hideBtn">Hide Paragraph</button></body></html>Let me know if you'd like syntax for specific use cases like animations, AJAX, or form handling!