jQuery uses a simple and concise syntax to interact with HTML elements, making tasks like DOM manipulation, event handling, and animations much easier.
Basic jQuery Syntax:
$(selector).action();
$
: The$
symbol is a shorthand for jQuery. It’s used to access jQuery functions.selector
: A string that specifies which HTML element(s) to select. It can be an element name, class, ID, or other CSS-like selectors.action
: The jQuery method to be performed on the selected element(s). For example, actions could include hiding elements, changing their style, or handling events.
Selectors in jQuery:
jQuery selectors allow you to select and manipulate HTML elements based on their attributes, classes, IDs, and more. These are similar to CSS selectors.
- ID Selector: Selects an element with a specific ID.
$("#myId").action();
- Class Selector: Selects elements with a specific class.
$(".myClass").action();
- Element Selector: Selects all elements of a specific type.
$("p").action();
- Universal Selector: Selects all elements.
$("*").action();
Common jQuery Methods:
- HTML/Content Manipulation:
html()
: Get or set the HTML content of an element.$("#example").html("<p>New content</p>");
text()
: Get or set the text content of an element.$("#example").text("New text");
val()
: Get or set the value of form fields.$("#inputField").val("New value");
- CSS Manipulation:
css()
: Get or set CSS properties.$("#example").css("color", "blue");
- Event Handling:
click()
: Attach a function to the click event of an element.$("#button").click(function(){ alert("Button clicked!"); });
hover()
: Attach functions for mouse enter and leave events.$("#example").hover(function(){ $(this).css("background-color", "yellow"); }, function(){ $(this).css("background-color", "white"); });
- Effects and Animations:
hide()
: Hide an element.$("#example").hide();
show()
: Show an element.$("#example").show();
fadeIn()
,fadeOut()
: Fade elements in or out.$("#example").fadeIn();
slideUp()
,slideDown()
: Slide elements up or down.$("#example").slideUp();
- AJAX Methods:
load()
: Load data from the server and place the returned HTML into an element.$("#example").load("data.html");
$.get()
,$.post()
: Perform AJAX GET or POST requests.$.get("url", function(data){ $("#example").html(data); });
Combining Actions (Chaining):
jQuery allows chaining multiple actions on the same element(s).
$("#example").css("color", "red").slideUp(2000).slideDown(2000);
In this example, the element with the ID example
changes color to red, slides up over 2 seconds, and then slides down over 2 seconds.
Document Ready Function:
Ensures that the DOM is fully loaded before executing jQuery code.
$(document).ready(function(){ // Your jQuery code here });
This is often written as a shorthand:
$(function(){ // Your jQuery code here });