menuMDUIDocs
color_lens
The new mdui 2 based on Material Design 3 and Web Components is now available. Check out the mdui 2 documentation.

JavaScript Utility Library

mdui has a built-in lightweight JavaScript utility library with a jQuery-like API and chaining style, but it is only one-sixth the size of jQuery.

You can use mdui.$ to call the library, but it's better to store mdui.$ in a short variable for convenience, for example:

var $ = mdui.$;

In the subsequent documentation, $ is used to represent mdui.$.

Core

$()

This method has multiple usages:

A CSS selector can be passed as a parameter to return a JQ object containing the matching elements. This method is implemented via querySelectorAll.

$('.box')

DOM elements, any array, NodeList, or JQ objects can be passed to return a JQ object containing the specified elements.

$(document)

An HTML string can be passed to return a JQ object containing the DOM created based on the HTML.

$('<div id="wrapper">
  <span id="inner"></span>
</div>')

A function can be passed, which will be called after the DOM is fully loaded.

$(function () { console.log('DOM Loaded') })

Plugin Writing

$.extend()

If only one object is passed, the properties in that object will be merged into the JQ object, which is equivalent to adding new functionality under the JQ namespace.

$.extend({
  customFunc: function () {}
})

// Then the custom method can be called like this
$.customFunc()

If two or more objects are passed, properties from all objects are added to the first object, and the merged object is returned.

var object = $.extend(
  { key1: val1 },
  { key2: val2 },
  { key3: val3 }
);

// In this case, both the first object and the return value are { key1: val1, key2: val2, key3: val3 }
$.fn.extend()

Extend methods on the JQ prototype chain.

$.fn.extend({
  customFunc: function () {}
})

// Then the extended method can be used like this
$(document).customFunc()

URL

$.param()

Serialize an object or array and return a string suitable for URL parameters.

$.param({ width: 1680, height: 1050 })
// width=1680&height=1050

$.param({ foo: { one: 1, two: 2 } })
// foo[one]=1&foo[two]=2

$.param({ ids: [1, 2, 3] })
// ids[]=1&ids[]=2&ids[]=3

If the parameter is an array, it must be in the same format as the return format of .serializeArray():

$.param([
  { "name": "name", "value": "mdui" },
  { "name": "password", "value": "123456" }
])
// name=mdui&password=123456

Array and Object Operations

$.each()

Traverse an array or object. The return value is the first parameter, i.e., the array or object being traversed.

The first parameter of the function is the index position of the array or the key of the object; the second parameter is the value at the corresponding position of the array or object.

The this in the callback function points to the value at the corresponding position of the array or object. If the callback function returns false, the traversal stops.

// Traverse an array
$.each(['a', 'b', 'c'], function (index, value) {
  console.log(index + ':' + value);
})

// Result:
// 0:a
// 1:b
// 2:c
// Traverse an object
$.each({'name': 'mdui', 'lang': 'zh'}, function (key, value) {
  console.log(key + ':' + value);
})

// Result:
// name:mdui
// lang:zh
$.merge()

Append elements of the second array to the first array and return the merged array.

var first = ['a', 'b', 'c'];
var second = ['c', 'd', 'e'];
var result = $.merge(first, second);

console.log(first); // ['a', 'b', 'c', 'c', 'd', 'e']
console.log(result); // ['a', 'b', 'c', 'c', 'd', 'e']
$.unique()

Filter out duplicate elements in the array.

var result = $.unique([1, 2, 12, 3, 2, 1, 2, 1, 1, 1, 1]);
console.log(result); // [1, 2, 12, 3]
$.map()

Traverse an array or object and return a new array composed of the return values of the function.

The first parameter of the function is the value at the corresponding position of the array or object, and the second parameter is the index position of the array or the key of the object.

The function can return any value. If it returns an array, it will be flattened; if it returns null or undefined, it will be ignored. this inside the function points to the window object.

// Traverse an array
var result = $.map(['a', 'b', 'c'], function (value, index) {
  return index + value;
});
console.log(result); // ['0a', '1b', '2c']
// When the callback function returns an array, it will be flattened
var result = $.map([1, 2, 3], function (value, index) {
  return [value, value + 1];
});
console.log(result); // [1, 2, 2, 3, 3, 4]
// Traverse an object
var result = $.map({ name: 'mdui', password: '123456' }, function (value, key) {
  return key + ':' + value;
});
console.log(result); // ['name:mdui', 'password:123456']
$.contains()

Determine whether a parent node contains a child node, returning a boolean value.

$.contains(document, document.body); // true
$.contains(document.body, document); // false

Data Type Checking

.is()

Returns true if at least one element in the collection matches the parameter, otherwise returns false.

The parameter can be a CSS selector, DOM element, array of DOM elements, JQ object, or callback function.

When the parameter is a callback function, its first parameter is the index position, the second parameter is the current element, and this points to the current element. If the function returns true, it indicates a match; if it returns false, it indicates no match.

$('.box').is('.box'); // true
$('.box').is('.boxss'); // false
$('.box').is($('.box')[0]); // true
// Determine by the return value of the callback function
$(document).is(function (index, element) {
  return element === document;
});
// true

Object Access

.length

Return the number of elements in the current collection.

$('body').length; // 1
.each()

Traverse the current collection and execute a function for each element in the collection. If the function returns false, the traversal ends.

The first parameter of the function is the index position of the element, and the second parameter is the current element. this in the function points to the current element.

$('img').each(function(index, element) {
  this.src = 'test' + index + '.jpg';
});
.map()

Traverse the current collection and execute a function for each element, returning a new collection composed of the function return values. If the function returns null or undefined, it will be filtered out.

The first parameter of the function is the index position of the element, and the second parameter is the current element. this in the function points to the current element.

var result = $('input.checked').map(function (index, element) {
  return $(this).val();
});

// result is a JQ object composed of the values of the matching elements
.eq()

Return a collection containing only the element at the specified index position.

$('div').eq(0); // Return a JQ object containing only the first element
$('div').eq(-1); // Return a JQ object containing only the last element
$('div').eq(-2); // Return a JQ object containing only the second-to-last element
.first()

Return a collection containing only the first element.

$('div').first(); // Return a JQ object containing only the first div
.last()

Return a collection containing only the last element.

$('div').last(); // Return a JQ object containing only the last div
.get()

Return the element at the specified index position. If no parameter is passed, return an array composed of all elements in the collection.

$('div').get(); // Return an array composed of all div elements
$('div').get(0); // Return the first div element
$('div').get(-1); // Return the last div element
.index()

If no parameter is passed, return the index position of the first element in the collection relative to its siblings.

If a CSS selector is passed as a parameter, return the index position of the first element in the collection relative to the elements matching the CSS selector.

If a DOM element is passed, return the index of that DOM element in the collection.

If a JQ object is passed, return the index position of the first element in that object within the current collection.

<div id="child">
  <div id="child1"></div>
  <div id="child2"></div>
  <div id="child3"></div>
  <div id="child4"></div>
</div>
$('#child3').index(); // 2
$('#child3').index('#child div'); // 2
$('#child div').index($('#child3').get(0)); // 2
.slice()

Return a subset of the current collection.

The first parameter is the start position of the subset, and the second parameter is the end position; if the second parameter is not passed, it includes all elements from the start position to the end.

// Return all elements after the third element (inclusive)
$('div').slice(3);

// Return elements between the third and fifth (inclusive of the third, exclusive of the fifth)
$('div').slice(3, 5);
.filter()

Filter elements matching the specified expression from the current collection. The parameter can be a CSS selector, DOM element, array of DOM elements, or callback function.

When the parameter is a function, its first parameter is the index position, the second parameter is the current element, and this in the function points to the current element. If the function returns true, the current element is kept; if it returns false, the current element is removed.

// Filter out all div elements containing .box
$('div').filter('.box');

// Filter out all selected options
$('#select option').filter(function (index, element) {
  return element.selected;
});
.not()

Filter elements from the current collection that do not match the specified expression. The parameter can be a CSS selector, DOM element, array of DOM elements, or callback function.

When the parameter is a function, its first parameter is the index position, the second parameter is the current element, and this in the function points to the current element. If the function returns true, the current element is removed; if it returns false, the current element is kept.

// Filter out all div elements that do not contain the .box class
$('div').not('.box');

// Filter out all unselected options
$('#select option').not(function (index, element) {
  return element.selected;
});

CSS Classes

.hasClass()

Determine whether the first element in the collection contains the specified CSS class.

// Determine whether the first div element contains .item
$('div').hasClass('item')
.addClass()

Add CSS classes to each element in the collection; multiple class names can be separated by spaces.

A callback function that returns CSS class names can also be passed. The first parameter of the function is the index position, the second parameter is the original CSS class name on the element, and this in the function points to the current element.

// Add .item to all div elements
$('div').addClass('item')
// Add .item1 and .item2 to all div elements
$('div').addClass('item1 item2')
// Add CSS classes returned by the callback function to all div elements
$('div').addClass(function (index, currentClassName) {
  return currentClassName + '-' + index;
})
.removeClass()

Remove CSS classes from elements in the collection; multiple class names can be separated by spaces.

A callback function that returns CSS class names can also be passed. The first parameter of the function is the index position, the second parameter is the original CSS class name on the element, and this in the function points to the current element.

If no parameter is passed, the class attribute on the element will be directly removed.

// Remove .item from all div elements
$('div').removeClass('item')
// Remove .item1 and .item2 from all div elements
$('div').removeClass('item1 item2')
// Remove CSS classes returned by the callback function from all div elements
$('div').removeClass(function (index, currentClassName) {
  return 'item';
})
// Directly remove the class attribute
$('div').removeClass()
.toggleClass()

Toggles a CSS class for elements in the collection: if the class is present, it is removed; otherwise, it is added. Multiple class names can be separated by spaces.

A callback function that returns CSS class names can also be passed. The first parameter of the function is the index position, the second parameter is the original CSS class name on the element, and this in the function points to the current element.

// Toggle .item on all div elements
$('div').toggleClass('item')
// Toggle .item1 and .item2 on all div elements
$('div').toggleClass('item1 item2')
// Toggle CSS classes returned by the callback function on all div elements
$('div').toggleClass(function (index, currentClassName) {
  return 'item';
})

Node Attributes

.prop()

Get the attribute value of the first element in the collection.

// Get the attribute value of the first element
$('input').prop('checked');

Can also set attribute values for all elements in the collection.

The attribute value can be the return value of a callback function. The first parameter of the callback function is the index position of the element, the second parameter is the original attribute value on the element, and this inside the function points to the current element.

If the attribute value or the return value of the callback function is void or undefined, the original attribute will not be modified.

Multiple attributes can also be set simultaneously by passing an object.

// Set attribute values for all selected elements
$('input').prop('checked', true);

// Set attribute values via the return value of the callback function
$('input').prop('checked', function (index, oldPropValue) {
  return true;
});

// Set multiple attribute values for an element simultaneously
$('input').prop({
  checked: false,
  disabled: function (index, oldPropValue) {
    return true;
  }
});
.removeProp()

Remove specified attribute values from all elements in the collection.

$('input').removeProp('disabled');
.attr()

Get the property value of the first element in the collection.

// Get the property value of the first element
$('div').attr('username');

Can also set property values for all elements in the collection.

The property value can be the return value of a callback function. The first parameter of the callback function is the index position of the element, the second parameter is the original property value on the element, and this inside the function points to the current element.

If the property value or the return value of the callback function is void or undefined, the original property will not be modified. If the property value or the return value of the callback function is null, the specified property will be removed.

Multiple properties can also be set simultaneously by passing an object.

// Set property values for all selected elements
$('div').attr('username', 'mdui');

// Set property values via the return value of the callback function
$('div').attr('username', function (index, oldAttrValue) {
  return 'mdui';
});

// Set multiple property values for an element simultaneously
$('div').attr({
  username: 'mdui',
  lastname: function (index, oldAttrValue) {
    return 'test';
  }
});
.removeAttr()

Remove specified property values from all elements in the collection; multiple property names can be separated by spaces.

// Remove a property from all elements in the collection
$('div').removeAttr('username');

// Remove multiple properties from all elements in the collection
$('div').removeAttr('username lastname');
.val()

Get the value of the first element in the collection.

If the element is <select multiple="multiple">, an array containing each selection will be returned.

// Get the value of the first selected element
$('#input').val();

Can also set values for all elements in the collection.

The value can be a string, number, array of strings, or a callback function.

If the value is a callback function, its first parameter is the index position of the element, the second parameter is the original value of the element, and this in the function points to the current element.

If the element is <input type="checkbox">, <input type="radio">, or <option>, the element value or function return value can be an array; in this case, elements with values in the array will be selected, and those with values not in the array will be deselected.

If the value or the function return value is undefined, the element value will be set to empty.

// Set the value of selected elements
$('#input').val('input value');

// Set the element value via the return value of the callback function
$('#input').val(function (index, oldValue) {
  return 'new value';
});
.text()

Get the text content of all elements in the collection (including their descendants)

// Get the text of all .box elements
$('.box').text();

Can also set the text for all elements in the collection.

The set value can be a string, number, boolean, or callback function.

If it is a callback function, the first parameter is the index position of the element, the second parameter is the original text content of the element, and this inside the function points to the current element.

If the value or the return value of the callback function is undefined, the text of the corresponding element will not be modified.

// Set the text content of selected elements
$('.box').text('text content');

// Set the text content of elements via the return value of the callback function
$('.box').text(function (index, oldTextContent) {
  return 'new text content';
});
.html()

Get the HTML content of the first element in the collection.

// Get the HTML content of the first .box element
$('.box').html();

Can also set the HTML content for all elements in the collection.

The set value can be an HTML string, DOM element, or callback function.

If it is a callback function, the first parameter is the index position of the element, the second parameter is the original HTML content of the element, and this inside the function points to the current element.

If the value or the function return value is undefined, the HTML of the corresponding element will not be modified.

// Set the HTML of selected elements
$('.box').html('<div>new html content</div>');

// Set the HTML content of elements via the return value of the callback function
$('.box').html(function (index, oldHTMLContent) {
  return '<div>new html content</div>';
});

Data Storage

$.data()

Read or store data on specified elements.

When storing data, if the value is undefined, it is equivalent to reading the corresponding data on the element. That is, $.data(element, 'key', undefined) is equivalent to $.data(element, 'key').

Note: This method does not retrieve data-* attributes on elements.

// Store data on the specified element and return the stored value
$.data(document.body, 'layout', 'dark'); // Return dark

// Store multiple data on the specified element simultaneously
$.data(document.body, {
  primary: 'indigo',
  accent: 'pink',
});

// Get the data stored on the specified element
$.data(document.body, 'layout'); // Return dark

// Get all data stored on the specified element
$.data(document.body); // Return { layout: 'dark', primary: 'indigo', accent: 'pink' }
$.removeData()

Remove data stored on specified elements.

Multiple keys can be separated by spaces, or represented by an array of multiple keys. When no keys are specified, all data on the element will be removed.

// Remove data with the key name "name" on the element
$.removeData(document.body, 'name');

// Remove data with key names "name1" and "name2" on the element. The following two methods are equivalent:
$.removeData(document.body, 'name1 name2');
$.removeData(document.body, ['name1', 'name2']);

// Remove all data stored on the element
$.removeData(document.body);
.data()

Read or store data on elements in the current collection.

When storing data, if the value is undefined, no storage will occur.

Note: The data retrieved by this method will include data-* attributes on the elements.

// Store data on elements in the current collection
$('.box').data('layout', 'dark');

// Store multiple data on elements in the current collection simultaneously
$('.box').data({
  primary: 'indigo',
  accent: 'pink',
});

// Get the specified data stored on the first element in the current collection
$('.box').data('layout'); // Return dark

// Get all data stored on the first element in the current collection
$('.box').data(); // Return { layout: 'dark', primary: 'indigo', accent: 'pink' }
.removeData()

Remove data stored on elements in the current collection.

Multiple keys can be separated by spaces, or represented by an array of multiple keys. When no keys are specified, all data on the elements will be removed.

Note: This method only removes data set via the .data() method and does not remove data on data-* attributes.

// Remove data with the key name "name"
$('.box').removeData('name');

// Remove data with key names "name1" and "name2". The following two methods are equivalent:
$('.box').removeData('name1 name2');
$('.box').removeData(['name1', 'name2']);

// Remove all data stored on the element
$('.box').removeData();

Styles

.css()

Get the CSS property value of the first element in the collection.

$('.box').css('color')

Can also set CSS property values for all elements in the collection.

The property value can be a string, number, or a callback function that returns a string or number.

If the property value is a callback function, its first parameter is the index position of the element, the second parameter is the original CSS property value of the element, and this in the function points to the current element.

If the property value or the callback function returns void, undefined, or null, the CSS property value of the current element will not be modified.

If the property value or callback function returns a number, px will be added as the unit. If the property cannot use px as a unit, the value will be converted directly to a string.

Multiple CSS properties can also be set simultaneously by passing an object of key-value pairs.

// Set style values for all elements in the collection
$('.box').css('color', 'red')

// Set style values for all elements via the return value of the callback function
$('.box').css('color', function (index, oldCSSValue) {
  return 'green';
});

// Set multiple styles simultaneously by passing an object
$('.box').css({
  'background-color': 'white',
  color: function (index, oldCSSValue) {
    return 'blue';
  },
});
.width()

Get the width (in pixels) of the first element in the collection, excluding padding, border, and margin.

$('.box').width();

Can also set the width for all elements in the collection (excluding the width of padding, border, and margin).

The value can be a string with a unit, a number, or a callback function returning a string with a unit or a number.

The first parameter of the callback function is the index position of the element, the second parameter is the original width value of the element, and this in the function points to the current element.

If the value or the return value of the callback function is a number, px will be automatically added as the unit.

If the value or the return value of the callback function is null or undefined, the width of the element will not be modified.

// Set the width of all elements in the collection
$('.box').width('20%');

// When the value is a number, the default unit is px
$('.box').width(10);

// Set length via the return value of the callback function
$('.box').width(function (index, oldWidth) {
  return 10;
});
.height()

Get the height (in pixels) of the first element in the collection, excluding padding, border, and margin.

$('.box').height();

Can also set the height for all elements in the collection (excluding the height of padding, border, and margin).

The value can be a string with a unit, a number, or a callback function returning a string with a unit or a number.

The first parameter of the callback function is the index position of the element, the second parameter is the original height value of the element, and this in the function points to the current element.

If the value or the return value of the callback function is a number, px will be automatically added as the unit.

If the value or the return value of the callback function is null or undefined, the height of the element will not be modified.

// Set the height of all elements in the collection
$('.box').height('20%');

// When the value is a number, the default unit is px
$('.box').height(10);

// Set height via the return value of the callback function
$('.box').height(function (index, oldHeight) {
  return 10;
});
.innerWidth()

Get the width (in pixels) of the first element in the collection, including padding but excluding border and margin.

$('.box').innerWidth();

Can also set the width of all elements in the collection (including padding but excluding border and margin).

The value can be a string with a unit, a number, or a callback function returning a string with a unit or a number.

The first parameter of the callback function is the index position of the element, the second parameter is the original width value of the element, and this in the function points to the current element.

If the value or the return value of the callback function is a number, px will be automatically added as the unit.

If the value or the return value of the callback function is null or undefined, the width of the element will not be modified.

// Set the width of all elements in the collection
$('.box').innerWidth('20%');

// When the value is a number, the default unit is px
$('.box').innerWidth(10);

// Set width via the return value of the callback function
$('.box').innerWidth(function (index, oldWidth) {
  return 10;
});
.innerHeight()

Get the height (in pixels) of the first element in the collection, including padding but excluding border and margin.

$('.box').innerHeight();

Can also set the height of all elements in the collection (including padding but excluding border and margin).

The value can be a string with a unit, a number, or a callback function returning a string with a unit or a number.

The first parameter of the callback function is the index position of the element, the second parameter is the original height value of the element, and this in the function points to the current element.

If the value or the return value of the callback function is a number, px will be automatically added as the unit.

If the value or the return value of the callback function is null or undefined, the height of the element will not be modified.

// Set the height of all elements in the collection
$('.box').innerHeight('20%');

// When the value is a number, the default unit is px
$('.box').innerHeight(10);

// Set height via the return value of the callback function
$('.box').innerHeight(function (index, oldHeight) {
  return 10;
});
.outerWidth()

Get the width (in pixels) of the first element in the collection, including padding and border but excluding margin. The parameter true can be passed to include the margin width.

// Width including padding and border
$('.box').outerWidth();

// Width including padding, border, and margin
$('.box').outerWidth(true);

Can also set the width of all elements in the collection (including padding and border but excluding margin; the second parameter can be true to include margin width).

The first parameter can be a string with a unit, a number, or a callback function returning a string with a unit or a number.

The first parameter of the callback function is the index position of the element, the second parameter is the original width of the element, and this in the function points to the current element.

If the value or the return value of the callback function is a number, px will be automatically added as the unit.

If the value or the return value of the callback function is null or undefined, the width of the element will not be modified.

// Set the width of all elements in the collection
$('.box').outerWidth('20%');

// When the value is a number, the default unit is px
$('.box').outerWidth(10);

// If the second parameter is true, the width will include margin
$('.box').outerWidth(10, true);

// Set width via the return value of the callback function
$('.box').outerWidth(function (index, oldWidth) {
  return 10;
});
.outerHeight()

Get the height (in pixels) of the first element in the collection, including padding and border but excluding margin. The parameter true can be passed to include the margin height.

// Height including padding and border
$('.box').outerHeight();

// Height including padding, border, and margin
$('.box').outerHeight(true);

Can also set the height of all elements in the collection (including padding and border but excluding margin; the second parameter can be true to include margin height).

The first parameter can be a string with a unit, a number, or a callback function returning a string with a unit or a number.

The first parameter of the callback function is the index position of the element, the second parameter is the original height of the element, and this in the function points to the current element.

If the value or the return value of the callback function is a number, px will be automatically added as the unit.

If the value or the return value of the callback function is null or undefined, the height of the element will not be modified.

// Set the height of all elements in the collection
$('.box').outerHeight('20%');

// When the value is a number, the default unit is px
$('.box').outerHeight(10);

// If the second parameter is true, the height will include margin
$('.box').outerHeight(10, true);

// Set height via the return value of the callback function
$('.box').outerHeight(function (index, oldWidth) {
  return 10;
});
.hide()

Hide all elements in the collection.

$('.box').hide();
.show()

Show all elements in the collection.

$('.box').show();
.toggle()

Toggle the display state of all elements in the collection.

$('.box').toggle();
.offset()

Get the coordinates of the first element in the collection relative to the document.

$('.box').offset(); // { top: 20, left: 30 }

Can also set the coordinates of all elements in the collection relative to the document.

The parameter is an object containing top and left properties, or a callback function returning an object in this format.

If the parameter is a callback function, the first parameter is the index position of the element, the second parameter is the original coordinates of the element, and this in the function points to the current element.

If the values of top or left in the parameter are undefined, the corresponding value will not be modified.

// Set the coordinates of all elements in the collection
$('.box').offset({ top: 20, left: 30 });

// Set element coordinates via the return value of the callback function
$('.box').offset(function (index, oldOffset) {
  return { top: 20, left: 30 };
});
.offsetParent()

Return the positioning parent of the first element in the collection — that is, the first ancestor element whose position is relative or absolute.

$('.box').offsetParent();
.position()

Get the offset of the first element in the collection relative to its parent element.

$('.box').position(); // { top: 20, left: 30 }

Finding Nodes

.find()

Find specified descendant nodes in all elements of the current collection based on a CSS selector.

// Find nodes containing .box among descendants of #box
$('#box').find('.box')
.children()

Get the collection of direct child elements from all elements in the current collection.

A CSS selector can be passed as a parameter to filter the child elements.

// Find all direct child elements of #box
$('#box').children();

// Find collection of elements containing .box among all direct child elements of #box
$('#box').children('.box')
.has()

Filter elements containing the specified child elements from all elements in the current collection.

Parameters can be CSS selectors or DOM elements.

// Add background color to li containing ul
$('li').has('ul').css('background-color', 'red');
.parent()

Get the collection of direct parent elements for all elements in the current collection.

A CSS selector can be passed as a parameter to return only the collection of parent elements matching that parameter.

// Return the direct parent element of .box elements
$('.box').parent();

// Return elements containing the .parent class among the direct parent elements of .box elements
$('.box').parent('.parent');
.parents()

Get the collection of ancestor elements for all elements in the current collection.

A CSS selector can be passed as a parameter to return only the collection of ancestor elements matching that parameter.

// Return all ancestor elements of span elements
$('span').parents();

// Return all ancestor elements of span elements that are p elements
$('span').parents('p');
.parentsUntil()

Get all parent elements of each element in the current collection until reaching an element matching the first parameter (matching element excluded).

The first parameter can be a CSS selector, DOM element, or JQ object.

An optional second parameter must be a CSS selector, indicating that only elements matching this parameter should be returned.

If no parameters are specified, all ancestor elements will be matched, which is the same as .parents().

// Get all ancestor elements of .item elements
$('.item').parentsUntil();

// Find all parent elements of .item elements until reaching the .parent element
$('.item').parentsUntil('.parent');

// Get all ancestor elements of .item elements that are div elements until reaching the .parent element
$('.item').parentsUntil('.parent', 'div');
.prev()

Get a collection of the previous sibling elements of all elements in the current collection.

A CSS selector can be passed as a parameter to get only the collection of sibling elements matching that parameter.

// Get the collection of previous elements for .box elements
$('.box').prev();

// Get the collection of previous div elements for .box elements
$('.box').prev('div');
.prevAll()

Get a collection of all previous sibling elements of all elements in the current collection.

A CSS selector can be passed as a parameter to get only the collection of sibling elements matching that parameter.

// Get all previous sibling elements of .box elements
$('.box').prevAll();

// Get all previous sibling elements of .box elements containing .selected
$('.box').prevAll('.selected');
.prevUntil()

Get all previous sibling elements of each element in the current collection until reaching an element matching the first parameter (matching element excluded).

The first parameter can be a CSS selector, DOM element, or JQ object.

An optional second parameter must be a CSS selector, indicating that only elements matching this parameter should be returned.

// Get all previous sibling elements of .box elements
$('.box').prevUntil();

// Get all previous sibling elements of .box elements until reaching the .until element
$('.box').prevUntil('.until');

// Get previous sibling div elements of .box elements until reaching the .until element
$('.box').prevUntil('.until', 'div');
.next()

Get a collection of the next sibling elements of all elements in the current collection.

A CSS selector can be passed as a parameter to get only the collection of sibling elements matching that parameter.

// Get the collection of next elements for .box elements
$('.box').next();

// Get the collection of next div elements for .box elements
$('.box').next('div');
.nextAll()

Get a collection of all subsequent sibling elements of all elements in the current collection.

A CSS selector can be passed as a parameter to get only the collection of sibling elements matching that parameter.

// Get all subsequent sibling elements of .box elements
$('.box').nextAll();

// Get all subsequent sibling elements of .box elements containing .selected
$('.box').nextAll('.selected');
.nextUntil()

Get all subsequent sibling elements of each element in the current collection until reaching an element matching the first parameter (matching element excluded).

The first parameter can be a CSS selector, DOM element, or JQ object.

An optional second parameter must be a CSS selector, indicating that only elements matching this parameter should be returned.

// Get all subsequent sibling elements of .box elements
$('.box').nextUntil();

// Get all subsequent sibling elements of .box elements until reaching the .until element
$('.box').nextUntil('.until');

// Get subsequent sibling div elements of .box elements until reaching the .until element
$('.box').nextUntil('.until', 'div');
.closest()

Match upwards from the current element level by level and return the first element matched.

Parameters can be CSS selectors, DOM elements, or JQ objects.

// Get the nearest .parent element among the parent elements of the .box element
$('.box').closest('.parent');
.siblings()

Get the sibling elements of each element in the current collection.

A CSS selector can be passed as a parameter to get only sibling elements matching that parameter.

// Get all sibling elements of .box elements
$('.box').siblings();

// Get elements containing .selected among all sibling elements of .box
$('.box').siblings('.selected');
.add()

Add elements to the current collection.

Parameters can be HTML strings, CSS selectors, JQ objects, DOM elements, arrays of DOM elements, or NodeList.

// Add elements containing .selected to the current collection
$('.box').add('.selected');

Node Manipulation

.empty()

Remove all child nodes from the current elements.

$('.box').empty();
.remove()

Remove elements in the current collection from the DOM.

A CSS selector can be passed as a parameter to remove only the elements matching that parameter.

// Remove all p elements
$('p').remove();

// Remove all p elements containing .box
$('p').remove('.box');
.prepend()

Insert specified content before the inside of the elements in the current collection.

Parameter types can be HTML strings, DOM elements, arrays of DOM elements, or JQ objects. Multiple parameters are supported.

A callback function returning an HTML string, DOM element, array of DOM elements, or JQ object can also be passed. The first parameter is the index position of the current element, the second parameter is the original HTML of the element, and this in the function points to the current element.

This method returns the original collection.

// Insert an element
$('<p>I would like to say: </p>').prepend('<b>Hello</b>');
// Result:<p><b>Hello</b>I would like to say: </p>

// Insert multiple elements
$('<p>I would like to say: </p>').prepend('<b>Hello</b>', '<b>World</b>');
// Result:<p><b>Hello</b><b>World</b>I would like to say: </p>

// Insert an element via a callback function
$('<p>Hello</p>').prepend(function (index, oldHTML) {
  return '<b>' + oldHTML + index + '</b>';
});
// Result:<p><b>Hello0</b>Hello</p>
.prependTo()

Prepend elements in the current collection to the inside of the specified elements.

Parameters can be CSS selectors, HTML strings, DOM elements, arrays of DOM elements, or JQ objects.

This method returns the original collection.

$('<div>Hello</div>').prependTo('<div>I would like to say: </div>');

// Result:[ <div><div>Hello</div>I would like to say: </div> ]
.append()

Insert specified content at the end of the inside of the elements in the current collection.

Parameter types can be HTML strings, DOM elements, arrays of DOM elements, or JQ objects. Multiple parameters are supported.

A callback function returning an HTML string, DOM element, array of DOM elements, or JQ object can also be passed. The first parameter is the index position of the current element, the second parameter is the original HTML of the element, and this in the function points to the current element.

This method returns the original collection.

// Insert an element
$('<p>I would like to say: </p>').append('<b>Hello</b>');
// Result:<p>I would like to say: <b>Hello</b></p>

// Insert multiple elements
$('<p>I would like to say: </p>').append('<b>Hello</b>', '<b>World</b>');
// Result:<p>I would like to say: <b>Hello</b><b>World</b></p>

// Insert an element via a callback function
$('<p>Hello</p>').append(function (index, oldHTML) {
  return '<b>' + oldHTML + index + '</b>';
});
// Result:<p>Hello<b>Hello0</b></p>
.appendTo()

Append elements in the current collection to the inside of the specified elements.

Parameters can be CSS selectors, HTML strings, DOM elements, arrays of DOM elements, or JQ objects.

This method returns the original collection.

$('<div>Hello</div>').appendTo('<div>I would like to say: </div>')
// Result:<div>I would like to say: <div>Hello</div></div>
.after()

Insert specified content after the current collection elements as sibling nodes.

Parameter types can be HTML strings, DOM elements, arrays of DOM elements, or JQ objects. Multiple parameters are supported.

A callback function returning an HTML string, DOM element, array of DOM elements, or JQ object can also be passed. The first parameter is the index position of the current element, the second parameter is the original HTML of the element, and this in the function points to the current element.

This method returns the original collection.

// Insert an element
$('<p>I would like to say: </p>').after('<b>Hello</b>')
// Result:<p>I would like to say: </p><b>Hello</b>

// Insert multiple elements
$('<p>I would like to say: </p>').after('<b>Hello</b>', '<b>World</b>')
// Result:<p>I would like to say: </p><b>Hello</b><b>World</b>

// Insert an element via a callback function
$('<p>Hello</p>').after(function (index, oldHTML) {
  return '<b>' + oldHTML + index + '</b>';
});
// Result:<p>Hello</p><b>Hello0</b>
.insertAfter()

Insert elements in the current collection after the target element as sibling elements.

If the elements in the current collection already exist in the page, they will be moved instead of copied. If there are multiple targets, the elements in the current collection will be cloned and added after each target element.

An HTML string, CSS selector, DOM element, array of DOM elements, or JQ object can be passed as a parameter to specify the target element.

$('<b>Hello</b>').insertAfter('<p>I would like to say: </p>');
// Result:<p>I would like to say: </p><b>Hello</b>
.before()

Insert specified content before the current collection elements as sibling nodes.

Parameter types can be HTML strings, DOM elements, arrays of DOM elements, or JQ objects. Multiple parameters are supported.

A callback function returning an HTML string, DOM element, array of DOM elements, or JQ object can also be passed. The first parameter is the index position of the current element, the second parameter is the original HTML of the element, and this in the function points to the current element.

This method returns the original collection.

// Insert an element
$('<p>I would like to say: </p>').before('<b>Hello</b>')
// Result:<b>Hello</b><p>I would like to say: </p>

// Insert multiple elements
$('<p>I would like to say: </p>').before('<b>Hello</b>', '<b>World</b>')
// Result:<b>Hello</b><b>World</b><p>I would like to say: </p>

// Insert an element via a callback function
$('<p>Hello</p>').before(function (index, oldHTML) {
  return '<b>' + oldHTML + index + '</b>';
});
// Result:<b>Hello0</b><p>Hello</p>
.insertBefore()

Insert elements in the current collection before the target element as sibling elements.

If the elements in the current collection already exist in the page, they will be moved instead of copied. If there are multiple targets, the elements in the current collection will be cloned and added after each target element.

An HTML string, CSS selector, DOM element, array of DOM elements, or JQ object can be passed as a parameter to specify the target element.

$('<p>I would like to say: </p>').insertBefore('<b>Hello</b>');
// Result:<p>I would like to say: </p><b>Hello</b>
.replaceWith()

Replace elements in the current collection with the specified elements.

Parameters can be HTML strings, DOM elements, arrays of DOM elements, or JQ objects.

A callback function returning an HTML string, DOM element, array of DOM elements, or JQ object can also be passed. The first parameter is the index position of the current element, the second parameter is the original HTML of the element, and this in the function points to the current element.

This method returns the original collection, i.e., the replaced collection.

// Replace all .box elements with <p>Hello</p>
$('.box').replaceWith('<p>Hello</p>');

// Replace all .box elements with the return value of the callback function
$('.box').replaceWith(function (index, oldHTML) {
  return oldHTML + index;
});
.replaceAll()

Replace specified elements with elements in the current collection.

Parameters are CSS selectors, DOM elements, arrays of DOM elements, or JQ objects.

This method returns the original collection, i.e., the collection of elements used for replacement.

// ${$t().a379}
$('.new').replaceAll('.box');
.clone()

Clone all elements in the collection via deep cloning.

Deep clone all elements in the collection using the native cloneNode method. This method does not copy data or event handlers to new elements, which differs from jQuery where parameters determine whether to copy data and event handlers.

$('body').append($("#box").clone())

Forms

.serializeArray()

Combine the values of form elements into an array of key-value pairs consisting of name and value.

This method can operate on individual form elements or entire <form> forms.

$('form').serializeArray();
// [
//   { "name": "golang", "value":"456" },
//   { "name": "name", "value": "mdui" },
//   { "name": "password", "value": "" }
// ]
.serialize()

Serialize the values of form elements.

$('form').serialize();
// golang=456&name=mdui&password=

Events

.on()

Bind event handlers to specific events for each element in the collection. See the examples below for specific usage:

// Bind click event
$('.box').on('click', function (e) {
  console.log('.box element clicked');
});

// Bind multiple events
$('.box').on('click focus', function (e) {
  console.log('Both click and focus events will trigger this function');
});

// Event delegation
$(document).on('click', '.box', function (e) {
  console.log('This function will be triggered when .box is clicked');
});

// Bind multiple events and event handlers simultaneously
$('.box').on({
  'click': function (e) {
    console.log('Click event triggered');
  },
  'focus': function (e) {
    console.log('Focus event triggered');
  }
});

// Pass parameters
$('.box').on('click', { key1: 'value1', key2: 'value2' }, function (e) {
  console.log('.box element clicked, and parameters were passed to the event handler');
  // e._data is {key1: 'value1', key2: 'value2'}
});

// Bind multiple events and event handlers simultaneously and pass parameters
$('.box').on({
  'click': function (e) {
    console.log('Click event triggered');
    // e._data is {key1: 'value1', key2: 'value2'}
  },
  'focus': function (e) {
    console.log('Focus event triggered');
    // e._data is {key1: 'value1', key2: 'value2'}
  }
}, { key1: 'value1', key2: 'value2' });

// Bind events via event delegation and pass parameters
$(document).on('click', '.box', { key1: 'value1', key2: 'value2' }, function (e) {
  console.log('.box element clicked, and parameters were passed to the event handler');
  // e._data is {key1: 'value1', key2: 'value2'}
});

// Bind multiple events and event handlers simultaneously via event delegation
$(document).on({
  'click': function (e) {
    console.log('Click event triggered');
  },
  'focus': function (e) {
    console.log('Focus event triggered');
  }
}, '.box');

// Bind multiple events and event handlers simultaneously via event delegation and pass parameters
$(document).on({
  'click': function (e) {
    console.log('Click event triggered');
    // e._data is {key1: 'value1', key2: 'value2'}
  },
  'focus': function (e) {
    console.log('Focus event triggered');
    // e._data is {key1: 'value1', key2: 'value2'}
  }
}, '.box', { key1: 'value1', key2: 'value2' });

// Get event parameters
$('.box').on('click', function (e, data) {
  // data is equal to e._detail
});

// Event names support namespaces
$('.box').on('click.myPlugin', function () {
  console.log('.box element clicked');
});
.one()

Bind event handlers for specific events on each matching element, but the event will only trigger once.

The usage of this method is the same as .on(), so no further examples are provided.

.off()

Unbind events for each element in the collection. See the examples below for specific usage:

// Unbind all bound event handlers
$('.box').off();

// Unbind specified events
$('.box').off('click');

// Unbind multiple events simultaneously
$('.box').off('click focus');

// Unbind specified event handlers
$('.box').off('click', callback);

// Unbind events bound via event delegation
$(document).off('click', '.box');

// Unbind specified event handlers bound via event delegation
$(document).off('click', '.box', callback);

// Unbind multiple event handlers simultaneously
$('.box').off({
  'click': callback1,
  'focus': callback2,
});

// Unbind multiple event handlers bound via event delegation simultaneously
$(document).off({
  'click': callback1,
  'focus': callback2,
}, '.box');

// Event names support namespaces; the following usage will unbind all events ending with .myPlugin
$(document).off('.myPlugin');
.trigger()

Trigger specified events. See the examples below for specific usage:

// Trigger specified events
$('.box').trigger('click');

// Pass parameters when triggering events
$('.box').trigger('click', { key1: 'value1', key2: 'value2' });

AJAX

$.ajaxSetup()

Set global configuration parameters for Ajax requests.

$.ajaxSetup({
  // Global AJAX events are disabled by default
  global: false,

  // POST request is used by default
  method: 'POST'
});

See the AJAX Parameters below for the detailed list of parameters.

$.ajax()

Send an AJAX request and return a Promise.

$.ajax({
  method: 'POST',
  url: './test.php',
  data: {
    key1: 'val1',
    key2: 'val2'
  },
  success: function (data) {
    console.log(data);
  }
});

See the AJAX Parameters below for the detailed list of parameters.

.ajaxStart()

Global AJAX events.

Execute a function when an AJAX request starts.

$(document).ajaxStart(function (event, xhr, options) {
  // xhr: XMLHttpRequest object
  // options: Configuration parameters for the AJAX request
});
.ajaxSuccess()

Global AJAX events.

Execute a function when an AJAX request is successful.

$(document).ajaxSuccess(function (event, xhr, options, data) {
  // xhr: XMLHttpRequest object
  // options: Configuration parameters for the AJAX request
  // data: Data returned from the AJAX request
});
.ajaxError()

Global AJAX events.

Execute a function when an AJAX request error occurs.

$(document).ajaxError(function (event, xhr, options) {
  // xhr: XMLHttpRequest object
  // options: Configuration parameters for the AJAX request
});
.ajaxComplete()

Global AJAX events.

Execute a function when an AJAX request is completed.

$(document).ajaxComplete(function (event, xhr, options) {
  // xhr: XMLHttpRequest object
  // options: Configuration parameters for the AJAX request
});

AJAX Parameters

Param NameTypeDefaultDescription
urlStringURL of the current page.The URL address for the request.
methodStringGET

Request method.

Includes: GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE

dataany''Data sent to the server.
processDataBooleantrueWhether to convert the passed-in data into a query string for sending.
asyncBooleantrueWhether the request is asynchronous.
cacheBooleantrueWhether to read from the cache. Only valid for GET and HEAD requests.
usernameString''Username for HTTP access authentication.
passwordString''Password for HTTP access authentication.
headersObject{}

Data added to Headers. This value can be overwritten in the beforeSend callback function.

Fields with string or null values will be sent, while fields with undefined values will be removed.

xhrFieldsObject{}

Data set on the XMLHttpRequest object.

$.ajax({
  url: 'A cross-origin URL',
  xhrFields: {
    withCredentials: true
  }
});
statusCodeObject{}

An object composed of HTTP status codes and functions.

$.ajax({
  statusCode: {
    404: function (xhr, textStatus) {
      alert('Called when the returned status code is 404');
    },
    200: function (data, textStatus, xhr) {
      alert('Called when the returned status code is 200');
    }
  }
});

If the status code is between 200 and 299, or if it is 304, it indicates a successful request, and the function parameters are the same as those for the success callback; otherwise, it indicates a failed request, and the function parameters are the same as those for the error callback.

dataTypeStringtext

Type of data returned by the server.

Includes: text, json

contentTypeStringapplication/x-www-form-urlencodedEncoding type of the content. If false, Content-Type will not be set.
timeoutNumber0Request timeout (milliseconds). 0 means no timeout.
globalBooleantrueWhether to trigger global AJAX events.
beforeSendFunction

Called before the request is sent. If it returns false, the AJAX request will be canceled.

$.ajax({
  beforeSend: function (xhr) {
    // xhr: XMLHttpRequest object
  }
});
successFunction

Called after the request is successful.

$.ajax({
  success: function (data, textStatus, xhr) {
    // data: Data returned from the AJAX request
    // textStatus: String containing the success code
    // xhr: XMLHttpRequest object
  }
});
errorFunction

Called when the request fails.

$.ajax({
  error: function (xhr, textStatus) {
    // xhr: XMLHttpRequest object
    // textStatus: String containing the success code
  }
});
completeFunction

Called after the request is completed.

$.ajax({
  complete: function (xhr, textStatus) {
    // xhr: XMLHttpRequest object
    // textStatus: String containing the success code
  }
});

More Common Methods

Note: These methods only exist in the mdui framework; they are not available if you use the mdui.jq library directly.

.reflow()

Force a repaint of the current element.

$('.box').reflow();
.transition()

Set the transition-duration property of the current element.

Can be a time value with or without a unit. If it has no unit, ms will be automatically added as the unit.

$('.box').transition(100);
.transitionEnd()

Add a transitionend event callback to the current element.

The parameter of the callback function is the transitionend event object, and this in the function points to the current element.

$('.box').transitionEnd(function () {
  console.log('The transitionend event for the .box element has been triggered');
})
.transform()

Set the transform property of the current element.

$('.box').transform('rotate(90deg)')
.transformOrigin()

Set the transform-origin property of the current element.

$('.box').transformOrigin('top center')
.mutation()

Execute initialization functions registered within the current element and its children.

$('[mdui-collapse]').mutation()
$.showOverlay()

Create and show an overlay, returning the JQ object of the overlay layer.

An integer parameter can be passed to represent the z-index style of the overlay layer, defaulting to 2000.

$.showOverlay();
$.hideOverlay()

Hide the overlay layer.

If $.showOverlay() is called multiple times to show the overlay layer, $.hideOverlay() must also be called the same number of times to hide it. Passing the parameter true forces the overlay to hide.

$.hideOverlay();
$.lockScreen()

Lock the page to prevent scrolling.

$.lockScreen();
$.unlockScreen()

Unlock the page.

If $.lockScreen() is called multiple times to lock the page, $.unlockScreen() must also be called the same number of times to unlock it. Passing the parameter true forces the page to unlock.

$.unlockScreen();
$.throttle()

Function throttling.

Pass a function as a parameter; the first parameter is the function to execute, and the second parameter is the delay time in milliseconds.

$.throttle(function () {
  console.log('This function executes at most once every 100ms');
}, 100)
$.guid()

Generate a globally unique ID.

$.guid();

A parameter can be passed. If the guid corresponding to that parameter value does not exist, a new guid is generated and returned; if it already exists, the existing guid is returned directly.

// The return values of the following two lines of code are the same.
$.guid('test');
$.guid('test');