TypeScript definitions for jQuery, the popular JavaScript library for DOM manipulation, event handling, and AJAX operations
—
jQuery provides comprehensive methods for modifying DOM structure, content, and attributes. The TypeScript types ensure type safety when manipulating elements and their properties.
interface JQuery<TElement = HTMLElement> {
// Get/set HTML content
html(): string;
html(htmlString: string): this;
html(func: (this: TElement, index: number, oldhtml: string) => string): this;
// Get/set text content
text(): string;
text(text: string | number | boolean): this;
text(func: (this: TElement, index: number, text: string) => string | number | boolean): this;
// Get/set form values
val(): string | number | string[];
val(value: string | number | string[]): this;
val(func: (this: TElement, index: number, value: string) => string | number): this;
}// HTML manipulation
const currentHtml = $('#container').html();
$('#container').html('<p>New HTML content</p>');
$('#container').html((index, oldHtml) => {
return oldHtml + '<p>Appended content</p>';
});
// Text manipulation
const currentText = $('#element').text();
$('#element').text('Plain text content');
$('#element').text((index, oldText) => {
return oldText.toUpperCase();
});
// Form value manipulation
const inputValue = $('#username').val() as string;
$('#username').val('john.doe');
$('#age').val(25);
// Multi-select values
const selectedValues = $('#multiselect').val() as string[];
$('#multiselect').val(['option1', 'option3']);
// Function-based value setting
$('input[type="text"]').val(function(index) {
return `Item ${index + 1}`;
});interface JQuery<TElement = HTMLElement> {
// Insert content inside elements
append(...contents: Array<string | Element | JQuery | ((this: TElement, index: number, html: string) => string | Element | JQuery)>): this;
appendTo(target: string | Element | JQuery): this;
prepend(...contents: Array<string | Element | JQuery | ((this: TElement, index: number, html: string) => string | Element | JQuery)>): this;
prependTo(target: string | Element | JQuery): this;
// Insert content adjacent to elements
after(...contents: Array<string | Element | JQuery | ((this: TElement, index: number) => string | Element | JQuery)>): this;
insertAfter(target: string | Element | JQuery): this;
before(...contents: Array<string | Element | JQuery | ((this: TElement, index: number) => string | Element | JQuery)>): this;
insertBefore(target: string | Element | JQuery): this;
}// Append content to elements
$('#container').append('<p>New paragraph</p>');
$('#container').append($('<div>').addClass('new-item'));
$('#container').append('<span>Text</span>', '<em>More text</em>');
// Function-based appending
$('.item').append(function(index) {
return `<span class="index">Item ${index}</span>`;
});
// Prepend content (insert at beginning)
$('#list').prepend('<li>First item</li>');
$('#container').prepend($('<header>').text('Container Header'));
// Insert adjacent content
$('#target').after('<div>Content after target</div>');
$('#target').before('<div>Content before target</div>');
// Reverse insertion (move elements to target)
$('<p>New paragraph</p>').appendTo('#container');
$('<li>New item</li>').prependTo('#list');
$('<span>After content</span>').insertAfter('#target');
$('<span>Before content</span>').insertBefore('#target');interface JQuery<TElement = HTMLElement> {
// Wrap each element
wrap(wrappingElement: string | Element | JQuery | ((this: TElement, index: number) => string | JQuery)): this;
// Wrap content inside elements
wrapInner(wrappingElement: string | Element | JQuery | ((this: TElement, index: number) => string | JQuery)): this;
// Wrap all elements together
wrapAll(wrappingElement: string | Element | JQuery | ((this: TElement) => string | JQuery)): this;
// Remove wrapping
unwrap(): this;
unwrap(selector: string): this;
}// Wrap each element individually
$('.item').wrap('<div class="wrapper"></div>');
$('.item').wrap($('<section>').addClass('item-section'));
// Function-based wrapping
$('.item').wrap(function(index) {
return `<div class="wrapper-${index}"></div>`;
});
// Wrap inner content
$('.container').wrapInner('<div class="inner-wrapper"></div>');
// Wrap all elements together as a group
$('.related-items').wrapAll('<div class="group-wrapper"></div>');
// Remove wrapping elements
$('.item').unwrap(); // Remove direct parent
$('.item').unwrap('.wrapper'); // Remove parent matching selectorinterface JQuery<TElement = HTMLElement> {
// Replace elements with new content
replaceWith(...newContent: Array<string | Element | JQuery | ((this: TElement, index: number, html: string) => string | Element | JQuery)>): this;
// Replace target elements with current selection
replaceAll(target: string | Element | JQuery): this;
}// Replace elements with new content
$('.old-item').replaceWith('<div class="new-item">Updated content</div>');
$('.old-item').replaceWith($('<span>').text('New span element'));
// Function-based replacement
$('.item').replaceWith(function(index) {
const content = $(this).text();
return `<p class="replaced">Item ${index}: ${content}</p>`;
});
// Replace target elements with current selection
$('<div class="replacement">New content</div>').replaceAll('.old-items');interface JQuery<TElement = HTMLElement> {
// Remove elements from DOM
remove(): this;
remove(selector: string): this;
// Remove elements but keep data and events
detach(): this;
detach(selector: string): this;
// Remove content but keep elements
empty(): this;
}// Remove elements completely (including data and events)
$('.unwanted').remove();
$('.item').remove('.disabled'); // Remove only disabled items
// Detach elements (preserves data and events for later reuse)
const detachedElements = $('.temporary').detach();
// Later: detachedElements.appendTo('#container');
// Empty elements (remove content but keep elements)
$('#container').empty();
$('.item-content').empty();interface JQuery<TElement = HTMLElement> {
// Get/set attributes
attr(attributeName: string): string | undefined;
attr(attributeName: string, value: string | number | null): this;
attr(attributes: JQuery.PlainObject<string | number | null>): this;
attr(attributeName: string, func: (this: TElement, index: number, attr: string) => string | number | null): this;
// Remove attributes
removeAttr(attributeName: string): this;
// Get/set properties
prop(propertyName: string): any;
prop(propertyName: string, value: any): this;
prop(properties: JQuery.PlainObject): this;
prop(propertyName: string, func: (this: TElement, index: number, prop: any) => any): this;
// Remove properties
removeProp(propertyName: string): this;
}// Get/set single attributes
const imgSrc = $('img').attr('src');
$('img').attr('src', '/images/new-image.jpg');
$('input').attr('placeholder', 'Enter your name');
// Set multiple attributes
$('input').attr({
'type': 'email',
'name': 'email',
'required': 'required',
'class': 'form-control'
});
// Function-based attribute setting
$('.item').attr('id', function(index) {
return `item-${index}`;
});
// Remove attributes
$('input').removeAttr('disabled');
$('img').removeAttr('width height');
// Properties (for DOM properties, not attributes)
const isChecked = $('#checkbox').prop('checked');
$('#checkbox').prop('checked', true);
$('select').prop('selectedIndex', 2);
// Multiple properties
$('input').prop({
'disabled': false,
'required': true
});
// Remove properties
$('input').removeProp('customProperty');interface JQuery<TElement = HTMLElement> {
// Add classes
addClass(classNames: string): this;
addClass(func: (this: TElement, index: number, currentClass: string) => string): this;
// Remove classes
removeClass(): this;
removeClass(classNames: string): this;
removeClass(func: (this: TElement, index: number, currentClass: string) => string): this;
// Toggle classes
toggleClass(): this;
toggleClass(classNames: string): this;
toggleClass(classNames: string, state: boolean): this;
toggleClass(func: (this: TElement, index: number, currentClass: string, state: boolean) => string): this;
toggleClass(state: boolean): this;
// Check for classes
hasClass(className: string): boolean;
}// Add classes
$('#element').addClass('active');
$('.item').addClass('selected highlighted');
$('.item').addClass('item-' + index);
// Function-based class addition
$('.item').addClass(function(index, currentClass) {
return currentClass + ' item-' + index;
});
// Remove classes
$('#element').removeClass('active');
$('.item').removeClass('selected highlighted');
$('.item').removeClass(); // Remove all classes
// Function-based class removal
$('.item').removeClass(function(index, currentClass) {
return currentClass.split(' ').filter(cls => cls.startsWith('temp-')).join(' ');
});
// Toggle classes
$('#element').toggleClass('active');
$('.item').toggleClass('selected', shouldBeSelected);
// Function-based toggle
$('.item').toggleClass(function(index, currentClass, state) {
return state ? 'active' : 'inactive';
});
// Check for classes
const isActive = $('#element').hasClass('active');
const hasMultiple = $('.item').hasClass('selected highlighted');interface JQuery<TElement = HTMLElement> {
// Get/set data
data(): JQuery.PlainObject;
data(key: string): any;
data(key: string, value: any): this;
data(obj: JQuery.PlainObject): this;
// Remove data
removeData(): this;
removeData(name: string): this;
removeData(list: string[]): this;
}// Set data values
$('#element').data('userId', 123);
$('#element').data('config', { theme: 'dark', lang: 'en' });
$('#element').data({
'itemId': 456,
'category': 'electronics',
'inStock': true
});
// Get data values
const userId = $('#element').data('userId') as number;
const config = $('#element').data('config') as { theme: string; lang: string };
const allData = $('#element').data() as JQuery.PlainObject;
// Data attributes (HTML5 data-* attributes)
$('#element').attr('data-user-id', '123');
const dataUserId = $('#element').data('userId'); // Auto-converted from data-user-id
// Remove data
$('#element').removeData('userId');
$('#element').removeData(['userId', 'config']);
$('#element').removeData(); // Remove all datainterface JQuery<TElement = HTMLElement> {
// Clone elements
clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): this;
}// Simple clone (structure only)
const cloned = $('.template').clone();
$('#container').append(cloned);
// Clone with events and data
const clonedWithEvents = $('.interactive-element').clone(true);
// Deep clone with events and data for all descendants
const deepCloned = $('.complex-widget').clone(true, true);
// Clone and modify
const newItem = $('.item-template')
.clone()
.removeClass('template')
.addClass('active-item')
.attr('id', 'item-' + newId);// Efficient batch operations
$('.items').each(function(index, element) {
const $element = $(element);
$element
.addClass(`item-${index}`)
.attr('data-index', index.toString())
.text(`Item ${index + 1}`);
});
// Conditional manipulation
$('.items').each(function(index) {
const $this = $(this);
if (index % 2 === 0) {
$this.addClass('even');
} else {
$this.addClass('odd');
}
});
// Chaining for efficiency
$('.products')
.addClass('product-item')
.attr('data-category', 'electronics')
.find('.price')
.addClass('price-display')
.end()
.find('.title')
.addClass('product-title');// Form element manipulation with type safety
interface FormElements {
inputs: JQuery<HTMLInputElement>;
selects: JQuery<HTMLSelectElement>;
textareas: JQuery<HTMLTextAreaElement>;
}
const form = {
inputs: $('input') as JQuery<HTMLInputElement>,
selects: $('select') as JQuery<HTMLSelectElement>,
textareas: $('textarea') as JQuery<HTMLTextAreaElement>
};
// Type-safe form manipulation
form.inputs.val('').attr('placeholder', 'Enter value');
form.selects.prop('selectedIndex', 0);
form.textareas.text('Default content');
// Image manipulation
const images = $('img') as JQuery<HTMLImageElement>;
images.attr({
'alt': 'Product image',
'loading': 'lazy'
}).on('load', function() {
$(this).addClass('loaded');
});function isInputElement(element: Element): element is HTMLInputElement {
return element.tagName === 'INPUT';
}
function isSelectElement(element: Element): element is HTMLSelectElement {
return element.tagName === 'SELECT';
}
// Usage with type guards
$('input, select').each(function() {
if (isInputElement(this)) {
// TypeScript knows this is HTMLInputElement
this.value = 'default';
} else if (isSelectElement(this)) {
// TypeScript knows this is HTMLSelectElement
this.selectedIndex = 0;
}
});// Batch DOM operations
const $container = $('#container');
const fragment = $(document.createDocumentFragment());
// Build content in memory first
for (let i = 0; i < 100; i++) {
fragment.append(`<div class="item">Item ${i}</div>`);
}
// Single DOM operation
$container.append(fragment);
// Cache jQuery objects
const $items = $('.item');
$items.addClass('processed').attr('data-processed', 'true');
// Chain operations efficiently
$('.product')
.addClass('enhanced')
.find('.price')
.addClass('highlighted')
.end()
.find('.description')
.addClass('expanded');The DOM manipulation API provides comprehensive methods for modifying element structure, content, and attributes with full type safety. These methods form the core of jQuery's power for dynamic web interfaces.
Install with Tessl CLI
npx tessl i tessl/npm-types--jquery