jQuery is a fast and lightweight JavaScript library designed to simplify HTML document traversal and manipulation, event handling, animation, and AJAX. Here’s a cheat sheet for common jQuery functions and syntax:
Getting Started
Include jQuery:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
Selectors
Select by Element:
$("p") // Selects all <p> elements
Select by ID:
$("#myId") // Selects element with id="myId"
Select by Class:
$(".myClass") // Selects all elements with class="myClass"
DOM Manipulation
Get/Set Text Content:
$("p").text() // Get text content
$("p").text("Hello, World!") // Set text content
Get/Set HTML Content:
$("div").html() // Get HTML content
$("div").html("<p>New HTML</p>") // Set HTML content
Get/Set Attribute:
$("img").attr("src") // Get attribute value
$("img").attr("src", "newimage.jpg") // Set attribute value
Add/Remove Classes:
$("div").addClass("highlight") // Add class
$("div").removeClass("highlight") // Remove class
Events
Click Event:
$("button").click(function(){
// Code to run on button click
});
Hover Event:
$("p").hover(function(){
// Code to run on hover
});
Keydown Event:
$(document).keydown(function(e){
// Code to run on keydown
});
Animations
Hide/Show:
$("div").hide() // Hide element
$("div").show() // Show element
Fade In/Fade Out:
$("div").fadeIn() // Fade in element
$("div").fadeOut() // Fade out element
Slide Up/Slide Down:
$("div").slideUp() // Slide up element
$("div").slideDown() // Slide down element
AJAX
Load Content:
$("div").load("content.html") // Load content from URL into div
AJAX GET Request:
$.get("data.json", function(data){
// Code to handle returned data
});
AJAX POST Request:
$.post("submit.php", { name: "John", age: 30 }, function(data){
// Code to handle returned data
});
Utility Functions
Each Iteration:
$("li").each(function(index){
// Code to run for each <li>
});
Filter Elements:
$("div").filter(".highlight") // Filters elements with class="highlight"
This is a cheat sheet for jQuery, covering commonly used functions. jQuery has a rich set of features, so refer to the official jQuery documentation for more in-depth information and examples.