getElementIndex
Returns the index of an element among its sibling elements.
1/**
2 * Returns the index of an element among its sibling elements.
3 *
4 * @param el - The DOM element.
5 * @returns The zero-based index of the element, or -1 if not in a parent.
6 */
7export function getElementIndex(el: Element): number {
8 if (!el.parentElement) return -1;
9 return Array.from(el.parentElement.children).indexOf(el);
10}
Straightforward Implementation
Uses native DOM APIs (
parentElement.children
andArray.from
) to deliver accurate results with minimal overhead.Handles Missing Parent Gracefully
Returns
-1
if the element has no parent, avoiding potential runtime errors.Zero-Based Consistency
Aligns with standard JavaScript indexing conventions, making the result intuitive for developers.
No External Dependencies
Pure, dependency-free logic ensures compatibility across environments and easy integration.
Tests | Examples
1test('getElementIndex - returns correct index among siblings', () => {
2 const container = document.createElement('div');
3 const el1 = document.createElement('div');
4 const el2 = document.createElement('div');
5 const el3 = document.createElement('div');
6
7 container.appendChild(el1);
8 container.appendChild(el2);
9 container.appendChild(el3);
10
11 expect(getElementIndex(el1)).toBe(0);
12 expect(getElementIndex(el2)).toBe(1);
13 expect(getElementIndex(el3)).toBe(2);
14});
15
16test('getElementIndex - returns -1 if no parent', () => {
17 const el = document.createElement('span');
18 expect(getElementIndex(el)).toBe(-1);
19});
Common Use Cases
Reordering Logic in UIs
Determine an element’s position before moving it within a list or grid.
Accessibility Indexing
Identify an element’s relative position for screen reader enhancements or tab indexing.
Custom Drag-and-Drop Implementations
Capture and compare DOM positions when dragging elements in sortable containers.
Dynamic Highlighting
Apply styles or behaviors based on an element’s index (e.g., alternate row coloring or animation delays).
Debugging and DOM Inspection
Quickly identify where a node appears among siblings for logging or inspection purposes.