This jQuery Cheat Sheet provides a comprehensive guide to using jQuery, including how to include it in your project, basic syntax, selectors, DOM manipulation, event handling, effects, AJAX, utilities, and best practices. It's designed to be a quick reference for developers to efficiently harness the power of jQuery in their web projects. Explore common methods, plugins, and additional resources to enhance your coding experience.
Include jQuery in your project
Using a CDN
One of the easiest ways to include jQuery in your project is by using a Content Delivery Network (CDN). Here’s how to do it:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Example</title>
<!-- jQuery CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello, jQuery!</h1>
<script>
$(document).ready(function(){
alert("jQuery is working!");
});
</script>
</body>
</html>
Downloading jQuery
You can also download jQuery and host it locally in your project:
- Go to the official jQuery website.
- Download the compressed, production jQuery version.
- Include the downloaded file in your project directory and reference it in your HTML:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Example</title>
<!-- Local jQuery -->
<script src="path/to/your/jquery.min.js"></script>
</head>
<body>
<h1>Hello, jQuery!</h1>
<script>
$(document).ready(function(){
alert("jQuery is working!");
});
</script>
</body>
</html>
Including jQuery in Node.js
If you are using Node.js, you can include jQuery using npm:
-
Install jQuery via npm:
npm install jquery
-
Use jQuery in your project:
const $ = require('jquery'); $(document).ready(function(){ console.log("jQuery is working in Node.js!"); });
Basic Syntax
Selecting Elements
jQuery uses CSS-style selectors to select elements in the DOM. Here are some common selectors:
// Select elements by tag name
$('p') // Selects all <p> elements
// Select elements by ID
$('#myId') // Selects the element with id="myId"
// Select elements by class
$('.myClass') // Selects all elements with class="myClass"
// Select elements by attribute
$('input[name="email"]') // Selects all <input> elements with name="email"
Chaining
jQuery allows you to chain multiple methods together. This makes your code more concise and readable.
// Example of method chaining
$('#myId').addClass('newClass').text('Hello, world!').show();
In this example:
$('#myId')
selects the element with id="myId"..addClass('newClass')
adds the class "newClass" to the selected element..text('Hello, world!')
sets the text of the selected element to "Hello, world!"..show()
displays the selected element if it was hidden.
Document Ready
To ensure your jQuery code runs after the DOM is fully loaded, use the $(document).ready()
function.
$(document).ready(function(){
// Your jQuery code here
console.log("The DOM is fully loaded.");
});
Alternatively, you can use the shorthand version:
$(function(){
// Your jQuery code here
console.log("The DOM is fully loaded.");
});
Basic Examples
Changing CSS
You can easily change the CSS of an element using jQuery.
$('p').css('color', 'red'); // Changes the text color of all <p> elements to red
Hiding and Showing Elements
You can hide or show elements using the hide()
and show()
methods.
$('#myId').hide(); // Hides the element with id="myId"
$('.myClass').show(); // Shows all elements with class="myClass"
Adding and Removing Classes
You can add or remove CSS classes using addClass()
and removeClass()
.
$('#myId').addClass('newClass'); // Adds the class "newClass" to the element with id="myId"
$('.myClass').removeClass('oldClass'); // Removes the class "oldClass" from all elements with class="myClass"
Selectors
Basic Selectors
$('element') // Selects all elements of the given type, e.g., $('p') selects all <p> elements
$('#id') // Selects the element with the specified id, e.g., $('#myId')
$('.class') // Selects all elements with the specified class, e.g., $('.myClass')
Attribute Selectors
$('[attribute]') // Selects elements with the specified attribute, e.g., $('[href]')
$('[attribute=value]') // Selects elements with the specified attribute value, e.g., $('[type="text"]')
$('[attribute!=value]') // Selects elements that do not match the attribute value, e.g., $('[type!="submit"]')
$('[attribute^=value]') // Selects elements with an attribute value that starts with a specified value, e.g., $('[name^="user"]')
$('[attribute$=value]') // Selects elements with an attribute value that ends with a specified value, e.g., $('[name$="name"]')
$('[attribute*=value]') // Selects elements with an attribute value that contains a specified value, e.g., $('[name*="man"]')
Hierarchy Selectors
$('parent > child') // Selects all child elements within a parent, e.g., $('ul > li') selects all <li> elements that are direct children of <ul>
$('ancestor descendant') // Selects all descendant elements, e.g., $('div p') selects all <p> elements inside <div> elements
$('prev + next') // Selects the next sibling element, e.g., $('h1 + p') selects the first <p> element that is immediately preceded by an <h1>
$('prev ~ siblings') // Selects all sibling elements after a previous element, e.g., $('h1 ~ p') selects all <p> elements that are siblings after an <h1>
Form Selectors
$(':input') // Selects all input, textarea, select, and button elements
$(':text') // Selects all input elements with type="text"
$(':password') // Selects all input elements with type="password"
$(':radio') // Selects all input elements with type="radio"
$(':checkbox') // Selects all input elements with type="checkbox"
$(':submit') // Selects all input elements with type="submit"
$(':reset') // Selects all input elements with type="reset"
$(':button') // Selects all button elements and input elements with type="button"
$(':image') // Selects all input elements with type="image"
$(':file') // Selects all input elements with type="file"
$(':enabled') // Selects all enabled input elements
$(':disabled') // Selects all disabled input elements
$(':selected') // Selects all selected options in a drop-down list
$(':checked') // Selects all checked checkboxes or radio buttons
Filter Selectors
$(':first') // Selects the first matched element
$(':last') // Selects the last matched element
$(':even') // Selects all even indexed elements (index starts at 0)
$(':odd') // Selects all odd indexed elements (index starts at 0)
$(':eq(index)') // Selects an element with a specific index, e.g., $('li:eq(2)') selects the third <li> element
$(':gt(index)') // Selects elements with an index greater than the specified index
$(':lt(index)') // Selects elements with an index less than the specified index
$(':not(selector)') // Selects elements that do not match the specified selector
$(':contains(text)') // Selects elements that contain the specified text
$(':has(selector)') // Selects elements that contain at least one element that matches the specified selector
$(':parent') // Selects elements that have at least one child element (including text nodes)
DOM Manipulation
Getting/Setting Content
Text Content
To get or set the text content of elements:
// Get the text content of an element
var text = $('#myElement').text();
// Set the text content of an element
$('#myElement').text('New text content');
HTML Content
To get or set the HTML content of elements:
// Get the HTML content of an element
var html = $('#myElement').html();
// Set the HTML content of an element
$('#myElement').html('<strong>New HTML content</strong>');
Value of Form Elements
To get or set the value of form elements:
// Get the value of an input element
var value = $('#myInput').val();
// Set the value of an input element
$('#myInput').val('New value');
Adding/Removing Elements
Append
To insert content at the end of the selected elements:
$('#myElement').append('<p>Appended content</p>');
Prepend
To insert content at the beginning of the selected elements:
$('#myElement').prepend('<p>Prepended content</p>');
After
To insert content after the selected elements:
$('#myElement').after('<p>Content after the element</p>');
Before
To insert content before the selected elements:
$('#myElement').before('<p>Content before the element</p>');
Remove
To remove the selected elements from the DOM:
$('#myElement').remove();
Empty
To remove all child elements and content from the selected elements:
$('#myElement').empty();
CSS Manipulation
Adding/Removing Classes
To add or remove CSS classes:
// Add a class
$('#myElement').addClass('newClass');
// Remove a class
$('#myElement').removeClass('oldClass');
// Toggle a class
$('#myElement').toggleClass('active');
CSS Properties
To get or set CSS properties:
// Get a CSS property value
var color = $('#myElement').css('color');
// Set a CSS property value
$('#myElement').css('color', 'red');
// Set multiple CSS properties
$('#myElement').css({
'background-color': 'blue',
'font-size': '16px'
});
Dimensions and Offsets
Width and Height
To get or set the width and height of elements:
// Get the width and height of an element
var width = $('#myElement').width();
var height = $('#myElement').height();
// Set the width and height of an element
$('#myElement').width(200); // Sets the width to 200 pixels
$('#myElement').height(100); // Sets the height to 100 pixels
Inner and Outer Dimensions
To get the inner and outer width/height, including padding and border:
// Get inner width/height (includes padding)
var innerWidth = $('#myElement').innerWidth();
var innerHeight = $('#myElement').innerHeight();
// Get outer width/height (includes padding and border)
var outerWidth = $('#myElement').outerWidth();
var outerHeight = $('#myElement').outerHeight();
// Get outer width/height with margin
var outerWidthWithMargin = $('#myElement').outerWidth(true);
var outerHeightWithMargin = $('#myElement').outerHeight(true);
Position and Offset
To get the position or offset of an element:
// Get the position (relative to the offset parent)
var position = $('#myElement').position();
// Get the offset (relative to the document)
var offset = $('#myElement').offset();
// Set the offset
$('#myElement').offset({ top: 10, left: 30 });
Events
Bind an Event
To attach an event handler to elements:
$('#myElement').on('click', function() {
alert('Element clicked!');
});
Unbind an Event
To remove an event handler from elements:
$('#myElement').off('click');
Click
To bind a function to the click event:
$('#myElement').click(function() {
alert('Element clicked!');
});
Double Click
To bind a function to the double-click event:
$('#myElement').dblclick(function() {
alert('Element double-clicked!');
});
Mouse Events
To bind functions to various mouse events:
$('#myElement').mouseenter(function() {
alert('Mouse entered!');
});
$('#myElement').mouseleave(function() {
alert('Mouse left!');
});
$('#myElement').hover(
function() {
alert('Mouse entered!');
},
function() {
alert('Mouse left!');
}
);
Keyboard Events
To bind functions to keyboard events:
$('#myInput').keypress(function(event) {
console.log('Key pressed: ' + event.which);
});
$('#myInput').keydown(function(event) {
console.log('Key down: ' + event.which);
});
$('#myInput').keyup(function(event) {
console.log('Key up: ' + event.which);
});
Form Events
To bind functions to form events:
$('#myForm').submit(function(event) {
event.preventDefault(); // Prevent the form from submitting
alert('Form submitted!');
});
$('#myInput').change(function() {
alert('Input value changed!');
});
$('#myInput').focus(function() {
console.log('Input focused!');
});
$('#myInput').blur(function() {
console.log('Input lost focus!');
});
Event Object Properties
When an event occurs, an event object is passed to the function that is handling the event. Here are some useful properties and methods:
$('#myElement').on('click', function(event) {
console.log(event.type); // Event type (e.g., 'click')
console.log(event.pageX); // Mouse position relative to the document (X coordinate)
console.log(event.pageY); // Mouse position relative to the document (Y coordinate)
console.log(event.which); // Which mouse button or key was pressed
console.log(event.target); // The DOM element that initiated the event
event.preventDefault(); // Prevent the default action of the event
event.stopPropagation(); // Stop the event from bubbling up the DOM tree
});
Event Delegation
Event delegation allows you to attach a single event listener to a parent element that manages all child elements, even those added in the future.
Example without Delegation
$('.child').on('click', function() {
alert('Child element clicked!');
});
Example with Delegation
$('#parent').on('click', '.child', function() {
alert('Child element clicked!');
});
This way, the event listener is attached to the parent element (#parent
), and it listens for click events on elements matching the .child
selector. This is more efficient and helps with dynamically added elements.
Effects and Animations
Hiding and Showing Elements
Hide
To hide elements:
$('#myElement').hide();
Show
To show hidden elements:
$('#myElement').show();
Toggle
To toggle the visibility of elements:
$('#myElement').toggle();
Fading
Fade In
To fade in elements:
$('#myElement').fadeIn('slow'); // or 'fast' or milliseconds, e.g., 2000
Fade Out
To fade out elements:
$('#myElement').fadeOut('slow'); // or 'fast' or milliseconds, e.g., 2000
Fade Toggle
To toggle the fading of elements:
$('#myElement').fadeToggle('slow'); // or 'fast' or milliseconds, e.g., 2000
Fade To
To fade elements to a specified opacity:
$('#myElement').fadeTo('slow', 0.5); // 'slow' or 'fast' or milliseconds, opacity value between 0 and 1
Sliding
Slide Down
To slide down (show) elements:
$('#myElement').slideDown('slow'); // or 'fast' or milliseconds, e.g., 2000
Slide Up
To slide up (hide) elements:
$('#myElement').slideUp('slow'); // or 'fast' or milliseconds, e.g., 2000
Slide Toggle
To toggle the sliding of elements:
$('#myElement').slideToggle('slow'); // or 'fast' or milliseconds, e.g., 2000
Custom Animations
Animate
To create custom animations for CSS properties:
$('#myElement').animate({
opacity: 0.5,
height: '50px'
}, 'slow'); // or 'fast' or milliseconds, e.g., 2000
Animate with Callback
To perform actions after an animation completes:
$('#myElement').animate({
opacity: 0.5,
height: '50px'
}, 'slow', function() {
alert('Animation complete!');
});
Animate with Easing
To specify an easing function for the animation:
$('#myElement').animate({
opacity: 0.5,
height: '50px'
}, {
duration: 'slow', // or 'fast' or milliseconds, e.g., 2000
easing: 'linear', // or 'swing' (default)
complete: function() {
alert('Animation complete!');
}
});
Stopping Animations
Stop
To stop the current animation:
$('#myElement').stop();
Stop with Parameters
To stop the current animation with options:
$('#myElement').stop(true, true); // The first 'true' clears the animation queue, the second 'true' jumps to the end of the current animation
Delays
Delay
To introduce a delay before the next animation:
$('#myElement').fadeIn('slow').delay(2000).fadeOut('slow'); // Delays the fade out by 2 seconds
Chaining Animations
jQuery allows chaining multiple methods together to create a sequence of animations and effects:
$('#myElement')
.fadeOut('slow')
.delay(1000)
.fadeIn('slow')
.slideUp('slow')
.slideDown('slow');
AJAX
Loading Data
.load()
To load data from the server and place the returned HTML into the matched elements:
$('#result').load('ajax/test.html');
You can also load a specific portion of the response using a selector:
$('#result').load('ajax/test.html #container');
Handling Responses
.get()
To make a GET request and handle the response:
$.get('ajax/test.html', function(data) {
$('#result').html(data);
});
.post()
To make a POST request and handle the response:
$.post('ajax/test.html', { key1: 'value1', key2: 'value2' }, function(data) {
$('#result').html(data);
});
AJAX Methods
.ajax()
The most flexible and powerful method is .ajax()
, which allows you to configure the entire AJAX request:
$.ajax({
url: 'ajax/test.html',
type: 'GET', // or 'POST'
data: {
key1: 'value1',
key2: 'value2'
},
success: function(data) {
$('#result').html(data);
},
error: function(xhr, status, error) {
console.log('Error: ' + error);
}
});
AJAX Convenience Methods
jQuery also provides several convenience methods that are shorthand for .ajax()
:
.getJSON()
To make a GET request and automatically parse the JSON response:
$.getJSON('ajax/test.json', function(data) {
console.log(data);
});
.getScript()
To load and execute a JavaScript file:
$.getScript('ajax/test.js', function() {
console.log('Script loaded and executed.');
});
Global AJAX Event Handlers
You can attach global event handlers that will be called for all AJAX requests:
.ajaxStart()
To run a function when an AJAX request starts:
$(document).ajaxStart(function() {
$('#loading').show();
});
.ajaxStop()
To run a function when all AJAX requests have completed:
$(document).ajaxStop(function() {
$('#loading').hide();
});
.ajaxError()
To handle AJAX errors:
$(document).ajaxError(function(event, jqxhr, settings, thrownError) {
console.log('AJAX error: ' + thrownError);
});
Additional AJAX Options
The .ajax()
method supports many options to configure the request. Here are some of the most useful ones:
dataType
To specify the type of data expected from the server:
$.ajax({
url: 'ajax/test.json',
dataType: 'json', // 'html', 'xml', 'script', 'json', 'jsonp', 'text'
success: function(data) {
console.log(data);
}
});
timeout
To set a timeout for the request (in milliseconds):
$.ajax({
url: 'ajax/test.html',
timeout: 5000, // 5 seconds
success: function(data) {
$('#result').html(data);
},
error: function(xhr, status, error) {
if (status === 'timeout') {
console.log('Request timed out');
} else {
console.log('Error: ' + error);
}
}
});
headers
To set custom headers for the request:
$.ajax({
url: 'ajax/test.html',
headers: {
'Custom-Header': 'value'
},
success: function(data) {
$('#result').html(data);
}
});
Utilities
Utility Methods
$.each()
To iterate over arrays and objects:
$.each([1, 2, 3], function(index, value) {
console.log(index + ': ' + value);
});
$.each({ name: 'John', age: 30 }, function(key, value) {
console.log(key + ': ' + value);
});
$.map()
To translate all items in an array or object to new arrays of items:
var numbers = [0, 1, 2];
var squares = $.map(numbers, function(value, index) {
return value * value;
});
console.log(squares); // [0, 1, 4]
$.grep()
To filter an array based on a condition:
var numbers = [0, 1, 2, 3, 4];
var evenNumbers = $.grep(numbers, function(value, index) {
return value % 2 === 0;
});
console.log(evenNumbers); // [0, 2, 4]
$.inArray()
To find the index of an item in an array:
var index = $.inArray(2, [1, 2, 3, 4]);
console.log(index); // 1
$.merge()
To merge the contents of two arrays together into the first array:
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
$.merge(array1, array2);
console.log(array1); // [1, 2, 3, 4, 5, 6]
$.extend()
To merge the contents of two or more objects together into the first object:
var object1 = { name: 'John' };
var object2 = { age: 30 };
$.extend(object1, object2);
console.log(object1); // { name: 'John', age: 30 }
$.isArray()
To check if an object is an array:
var isArray = $.isArray([1, 2, 3]);
console.log(isArray); // true
$.isFunction()
To check if an object is a function:
var isFunction = $.isFunction(function() {});
console.log(isFunction); // true
$.isPlainObject()
To check if an object is a plain object (created using "{}" or "new Object"):
var isPlainObject = $.isPlainObject({ name: 'John' });
console.log(isPlainObject); // true
Data Methods
.data()
To store arbitrary data associated with the matched elements:
$('#myElement').data('key', 'value');
var value = $('#myElement').data('key');
console.log(value); // 'value'
.removeData()
To remove a previously stored piece of data:
$('#myElement').removeData('key');
var value = $('#myElement').data('key');
console.log(value); // undefined
Deferred Objects
Deferred objects are used to manage asynchronous operations. They allow you to attach multiple callbacks and handle different states of the asynchronous operation.
$.Deferred()
To create a new deferred object:
var deferred = $.Deferred();
deferred.done()
To add a callback to be called when the deferred object is resolved:
deferred.done(function() {
console.log('Deferred resolved!');
});
deferred.fail()
To add a callback to be called when the deferred object is rejected:
deferred.fail(function() {
console.log('Deferred rejected!');
});
deferred.resolve()
To resolve the deferred object and call the done callbacks:
deferred.resolve();
deferred.reject()
To reject the deferred object and call the fail callbacks:
deferred.reject();
deferred.promise()
To get a promise object which provides a subset of the deferred methods:
var promise = deferred.promise();
promise.done(function() {
console.log('Promise resolved!');
});
$.when()
To manage multiple deferred objects:
$.when($.ajax('page1.html'), $.ajax('page2.html')).done(function(response1, response2) {
console.log('Both AJAX calls completed!');
});
Commonly Used Methods
Traversing
.find()
To find all descendant elements that match the selector:
$('#myElement').find('.child');
.children()
To get the direct children of each element in the set of matched elements:
$('#myElement').children('.child');
.parent()
To get the parent of each element in the set of matched elements:
$('.child').parent();
.siblings()
To get the siblings of each element in the set of matched elements:
$('#myElement').siblings();
.closest()
To get the first ancestor of each element in the set of matched elements:
$('.child').closest('.parent');
.next()
To get the immediately following sibling of each element in the set of matched elements:
$('#myElement').next();
.prev()
To get the immediately preceding sibling of each element in the set of matched elements:
$('#myElement').prev();
.filter()
To reduce the set of matched elements to those that match the selector or pass the function's test:
$('li').filter('.active');
.not()
To remove elements from the set of matched elements:
$('li').not('.active');
.eq()
To reduce the set of matched elements to the one at the specified index:
$('li').eq(1); // Selects the second <li> element
Manipulation
.append()
To insert content at the end of each element in the set of matched elements:
$('#myElement').append('<p>Appended content</p>');
.prepend()
To insert content at the beginning of each element in the set of matched elements:
$('#myElement').prepend('<p>Prepended content</p>');
.before()
To insert content before each element in the set of matched elements:
$('#myElement').before('<p>Content before</p>');
.after()
To insert content after each element in the set of matched elements:
$('#myElement').after('<p>Content after</p>');
.remove()
To remove the set of matched elements from the DOM:
$('#myElement').remove();
.empty()
To remove all child nodes of the set of matched elements from the DOM:
$('#myElement').empty();
.clone()
To create a deep copy of the set of matched elements:
var $clone = $('#myElement').clone();
.replaceWith()
To replace each element in the set of matched elements with new content:
$('#myElement').replaceWith('<p>New content</p>');
Events
.on()
To attach an event handler function for one or more events to the selected elements:
$('#myElement').on('click', function() {
alert('Element clicked!');
});
.off()
To remove an event handler:
$('#myElement').off('click');
.trigger()
To execute all handlers and behaviors attached to the matched elements for the given event type:
$('#myElement').trigger('click');
.hover()
To bind one or two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements:
$('#myElement').hover(
function() {
console.log('Mouse entered');
},
function() {
console.log('Mouse left');
}
);
Effects
.show()
To display the matched elements:
$('#myElement').show();
.hide()
To hide the matched elements:
$('#myElement').hide();
.toggle()
To display or hide the matched elements:
$('#myElement').toggle();
.fadeIn()
To fade in the matched elements:
$('#myElement').fadeIn('slow');
.fadeOut()
To fade out the matched elements:
$('#myElement').fadeOut('slow');
.slideDown()
To slide down the matched elements:
$('#myElement').slideDown('slow');
.slideUp()
To slide up the matched elements:
$('#myElement').slideUp('slow');
AJAX
.load()
To load data from the server and place the returned HTML into the matched elements:
$('#result').load('ajax/test.html');
.get()
To make a GET request:
$.get('ajax/test.html', function(data) {
$('#result').html(data);
});
.post()
To make a POST request:
$.post('ajax/test.html', { key1: 'value1', key2: 'value2' }, function(data) {
$('#result').html(data);
});
Best Practices
1. Minimize DOM Access
Accessing the DOM can be slow, so minimize the number of times you interact with it.
Bad:
$('#myElement').text('Hello');
$('#myElement').addClass('active');
$('#myElement').css('color', 'red');
Good:
var $element = $('#myElement');
$element.text('Hello');
$element.addClass('active');
$element.css('color', 'red');
2. Cache jQuery Selectors
Store jQuery selectors in variables to avoid redundant DOM queries.
Bad:
for (var i = 0; i < 10; i++) {
$('#myElement').append('<p>' + i + '</p>');
}
Good:
var $element = $('#myElement');
for (var i = 0; i < 10; i++) {
$element.append('<p>' + i + '</p>');
}
3. Use Event Delegation
For dynamically added elements, use event delegation to improve performance.
Bad:
$('.item').on('click', function() {
console.log('Item clicked');
});
Good:
$(document).on('click', '.item', function() {
console.log('Item clicked');
});
4. Optimize Selectors
Use specific selectors to reduce the time taken to find elements in the DOM.
Bad:
$('div').css('color', 'red'); // Selects all <div> elements
Good:
$('#myDiv').css('color', 'red'); // Selects a specific element with id="myDiv"
5. Chain Methods
Chain multiple methods together to make the code more concise and efficient.
Bad:
$('#myElement').show();
$('#myElement').text('Hello');
$('#myElement').addClass('active');
Good:
$('#myElement').show().text('Hello').addClass('active');
6. Use $(document).ready()
Ensure that your jQuery code runs only after the DOM is fully loaded.
Bad:
console.log($('#myElement').text()); // May not work if the element is not yet loaded
Good:
$(document).ready(function() {
console.log($('#myElement').text());
});
7. Use .html()
and .text()
Safely
When setting HTML content, be cautious of potential security risks such as XSS attacks.
Bad:
$('#content').html('<script>alert("XSS")</script>'); // Potentially unsafe
Good:
$('#content').text('<script>alert("XSS")</script>'); // Escapes the content
8. Avoid Using Inline Styles
It's better to use CSS classes rather than inline styles for maintainability and separation of concerns.
Bad:
$('#myElement').css('color', 'red').css('font-size', '14px');
Good:
$('#myElement').addClass('red-text small-text');
9. Keep jQuery Up-to-Date
Use the latest stable version of jQuery to benefit from performance improvements and security patches.
Bad:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Good:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
10. Use .prop()
Instead of .attr()
for Properties
For properties such as checked, disabled, and selected, use .prop()
instead of .attr()
.
Bad:
$('#myCheckbox').attr('checked', true);
Good:
$('#myCheckbox').prop('checked', true);
References
Official jQuery Documentation
The official jQuery documentation is the most comprehensive and authoritative source of information on jQuery. It provides detailed descriptions, examples, and API references for all jQuery functions, methods, and features.
Popular jQuery Plugins
jQuery's plugin ecosystem extends its functionality with a wide range of additional features. Here are some popular jQuery plugins:
-
jQuery UI: A curated set of user interface interactions, effects, widgets, and themes built on top of jQuery.
-
DataTables: A powerful plugin for creating dynamic and interactive HTML tables.
-
Slick Carousel: A responsive carousel jQuery plugin that supports multiple breakpoints, variable width, and more.
-
Select2: A jQuery-based replacement for select boxes that supports searching, tagging, remote data sets, and infinite scrolling.
-
jQuery Validation: A plugin for form validation with a large set of validation rules and customizable messages.
Additional Learning Resources
-
Books
- "jQuery in Action" by Bear Bibeault and Yehuda Katz
- "Learning jQuery" by Jonathan Chaffer and Karl Swedberg
- "JavaScript and jQuery: Interactive Front-End Web Development" by Jon Duckett
-
Online Tutorials
-
Video Tutorials
Community and Support
-
Forums and Discussion Groups
-
GitHub
- jQuery GitHub Repository
- Browse issues, contribute to the development, and view the latest updates.
-
Social Media
- Follow @jquery on Twitter for the latest news and updates.