or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

attributes.mdcore-selection.mdcss.mddata.mddimensions.mdeffects.mdevents.mdforms.mdindex.mdmanipulation.mdtraversal.mdutilities.md
tile.json

core-selection.mddocs/

Core Selection and Collections

Essential DOM selection and collection manipulation functionality, including the main constructor function and array-like operations on element collections.

Capabilities

Main Constructor Function

The primary Cash DOM constructor function for creating element collections.

/**
 * Create a Cash collection from various inputs
 * @param selector - CSS selector, HTML string, DOM element(s), function for ready, or existing collection
 * @param context - Optional search context (Document, HTMLElement, Element, or Cash collection)
 * @returns Cash collection instance
 */
function $(selector?: Selector, context?: Context | Cash): Cash;

Usage Examples:

// CSS selector
const divs = $('div');
const buttons = $('.button');
const header = $('#header');

// With context
const links = $('a', document.querySelector('.nav'));
const contextual = $('span', $('.container'));

// HTML string creation
const newElement = $('<div class="created">New content</div>');
const multipleElements = $('<p>First</p><p>Second</p>');

// DOM element wrapping
const wrapped = $(document.getElementById('myElement'));
const fromNodeList = $(document.querySelectorAll('.items'));

// Array of elements
const elements = [document.body, document.head];
const collection = $(elements);

// DOM ready callback
$(function() {
  console.log('DOM is ready');
});

// Existing collection (returns same instance)
const existing = $('.items');
const same = $(existing); // same === existing

Collection Addition

Add elements to an existing collection, returning a new collection with the combined elements.

/**
 * Add elements to the collection
 * @param selector - Elements to add (CSS selector, HTML string, DOM elements, or collection)
 * @param context - Optional search context for selector strings
 * @returns New Cash collection with added elements
 */
add(selector: Selector, context?: Context): Cash;

Usage Examples:

// Add elements by selector
const combined = $('.items').add('.more-items');

// Add specific elements
const withHeader = $('.content').add(document.querySelector('header'));

// Add with context
const scoped = $('.primary').add('li', document.querySelector('.secondary'));

// Chain with other operations
const result = $('.first')
  .add('.second')
  .add('.third')
  .addClass('combined');

Collection Iteration

Iterate over elements in the collection with a callback function.

/**
 * Iterate over each element in the collection
 * @param callback - Function called for each element (this: element, index, element)
 * @returns The same Cash collection for chaining
 */
each(callback: EachCallback<EleLoose>): this;

Usage Examples:

// Basic iteration
$('.items').each(function(index, element) {
  console.log(`Item ${index}:`, element.textContent);
});

// Using arrow functions
$('.buttons').each((index, button) => {
  button.addEventListener('click', () => console.log(`Button ${index} clicked`));
});

// Early exit by returning false
$('.list-items').each(function(index, item) {
  if (item.classList.contains('target')) {
    return false; // Stop iteration
  }
  // Process other items
});

Element Access by Index

Get a specific element from the collection by its index.

/**
 * Get element at specific index as a new Cash collection
 * @param index - Zero-based index of element to get
 * @returns New Cash collection containing only the element at index
 */
eq(index: number): Cash;

Usage Examples:

// Get first element as collection
const first = $('.items').eq(0);

// Get last element (negative indices work)
const last = $('.items').eq(-1);

// Get middle element
const middle = $('.items').eq(2);

// Chain with other methods
$('.tabs').eq(1).addClass('active').show();

Collection Filtering

Filter elements in the collection based on a selector or predicate function.

/**
 * Filter the collection based on a comparator
 * @param comparator - CSS selector, element, collection, or predicate function
 * @returns New Cash collection with filtered elements
 */
filter(comparator?: Comparator): Cash;

Usage Examples:

// Filter by CSS selector
const visible = $('.items').filter(':visible');
const active = $('.buttons').filter('.active');

// Filter by predicate function
const large = $('.boxes').filter(function(index, element) {
  return element.offsetWidth > 100;
});

// Filter by element presence
const specific = $('.items').filter(document.getElementById('target'));

// Filter by another collection
const matching = $('.all').filter($('.selected'));

First and Last Elements

Get the first or last element from the collection.

/**
 * Get the first element as a new Cash collection
 * @returns New Cash collection containing only the first element
 */
first(): Cash;

/**
 * Get the last element as a new Cash collection  
 * @returns New Cash collection containing only the last element
 */
last(): Cash;

Usage Examples:

// Get first element
const firstItem = $('.menu-items').first();

// Get last element
const lastItem = $('.menu-items').last();

// Chain operations
$('.tabs').first().addClass('first-tab');
$('.items').last().css('margin-bottom', 0);

Element Retrieval

Get elements from the collection as plain DOM nodes or arrays.

/**
 * Get all elements as a plain array
 * @returns Array of DOM elements
 */
get(): EleLoose[];

/**
 * Get element at specific index as a plain DOM node
 * @param index - Zero-based index of element to get  
 * @returns DOM element at index or undefined
 */
get(index: number): EleLoose | undefined;

Usage Examples:

// Get all elements as array
const elements = $('.items').get();
elements.forEach(el => console.log(el.tagName));

// Get specific element
const firstElement = $('.items').get(0);
if (firstElement) {
  firstElement.focus();
}

// Get last element with negative index
const lastElement = $('.items').get(-1);

// Use in vanilla JS operations
const nodeArray = $('.selected').get();
nodeArray.map(el => el.id);

Collection Mapping

Transform each element using a callback function, returning a new collection.

/**
 * Create a new collection by mapping over each element
 * @param callback - Function to transform each element (this: element, index, element)
 * @returns New Cash collection with mapped elements
 */
map(callback: MapCallback<EleLoose>): Cash;

Usage Examples:

// Map to parent elements
const parents = $('.items').map(function(index, element) {
  return element.parentElement;
});

// Map to related elements
const labels = $('.inputs').map((index, input) => 
  document.querySelector(`label[for="${input.id}"]`)
);

// Map with transformation
const siblings = $('.active').map(function(index, element) {
  return $(element).next().get(0);
});

Collection Slicing

Extract a portion of the collection based on start and end indices.

/**
 * Extract a slice of the collection
 * @param start - Starting index (inclusive)
 * @param end - Ending index (exclusive)
 * @returns New Cash collection with sliced elements
 */
slice(start?: number, end?: number): Cash;

Usage Examples:

// Get first 3 elements
const firstThree = $('.items').slice(0, 3);

// Get elements from index 2 onwards
const fromSecond = $('.items').slice(2);

// Get middle elements
const middle = $('.items').slice(1, -1);

// Get last 2 elements
const lastTwo = $('.items').slice(-2);

Element Index

Get the index of an element within its parent or within another collection.

/**
 * Get the index of the first element in the collection
 * @param selector - Optional selector or element to find index within
 * @returns Zero-based index of the element
 */
index(selector?: Selector): number;

Usage Examples:

// Get index among siblings
const siblingIndex = $('.current').index();

// Get index within a specific parent
const indexInParent = $('.item').index('.container .item');

// Get index of element in collection
const items = $('.all-items');
const selectedIndex = $('.selected').index(items);

// Use for navigation
$('.tab').on('click', function() {
  const tabIndex = $(this).index();
  $('.panel').eq(tabIndex).show().siblings().hide();
});

Collection Extension

Extend the collection instance with additional methods or properties from plugins.

/**
 * Extend the collection with plugin methods
 * @param plugins - Object containing methods/properties to add
 * @returns The Cash collection for chaining
 */
extend(plugins: Record<any, any>): this;

Usage Examples:

// Add custom methods to a collection instance
const $elements = $('.items');
$elements.extend({
  highlight: function() {
    return this.addClass('highlighted');
  },
  dim: function() {
    return this.removeClass('highlighted');
  }
});

// Use the extended methods
$elements.highlight();

// Plugin pattern with extend
$.fn.extend({
  fadeToggle: function(duration = 300) {
    return this.each(function() {
      const $el = $(this);
      if ($el.css('display') === 'none') {
        $el.show();
      } else {
        $el.hide();
      }
    });
  }
});

// Usage after extending prototype
$('.modal').fadeToggle();

Types

type EachCallback<T> = (this: T, index: number, ele: T) => any;
type MapCallback<T> = (this: T, index: number, ele: T) => Ele;