Query - Iterators API reference for Query iterator methods repeat API Reference
Categories

Query - Iterators

Iterator methods in Query allow you to loop through, manipulate, and filter sets of elements efficiently.

each

Iterates over a Query object, executing a function for each matched element.

Syntax

$('selector').each(function(element, index) {
// Your code here
})

Parameters

NameTypeDescription
functionFunctionFunction to execute for each element

Returns

Query object (for chaining).

Usage

$('div').each(function(el, index) {
console.log(`Div ${index}:`, el.textContent);
});

Example

Execution Context Inside the callback, this refers to the current DOM element.

map

Creates a new array with the results of calling a provided function on every element in the set.

Syntax

$('selector').map(function(element, index) {
// Your code here
return someValue;
})

Parameters

NameTypeDescription
functionFunctionFunction to execute for each element

Returns

A new array with the results of the function calls.

Usage

const textContents = $('p').map(function(el, index) {
return el.textContent;
});
console.log(textContents);

Example

Return Values The map() method collects the return value of your callback function for each element into a new array.

filter

Creates a new Query object with all elements that pass the test implemented by the provided function.

Syntax

$('selector').filter(function(element, index) {
// Your code here
return true; // or false
})

Parameters

NameTypeDescription
functionFunction or StringFunction or selector to test elements

Returns

A new Query object with the filtered elements.

Usage

const visibleElements = $('div').filter(function(el) {
return $(el).css('display') !== 'none';
});

Flexible Filtering You can pass either a function or a selector string to filter(). When using a function, return true to include the element, false to exclude it.

get

Retrieve the DOM element at the specified index, or all DOM elements if no index is provided.

Syntax

$('selector').get(index)
$('selector').get()

Parameters

NameTypeDescription
indexNumber(Optional) Zero-based index of the element to retrieve

Returns

  • With index: The DOM element at the specified index, or undefined if the index is out of range
  • Without index: An array of all DOM elements in the Query object

Usage

Get Single Element

// Get the first paragraph element
const firstPara = $('p').get(0);
console.log(firstPara.textContent);
// Get the last paragraph element
const lastPara = $('p').get(-1);
console.log(lastPara.textContent);

Get All Elements

// Get all paragraph elements as an array
const allParas = $('p').get();
allParas.forEach(para => {
console.log(para.textContent);
});

Example

Native DOM The get() method returns native DOM elements, not Query objects. Use this when you need to work with the raw DOM API.

Previous
Events
Next
Logical Operators