Skip to main content

Overview

The getElement method retrieves a single element from a block based on type, path, or custom matcher.

Signature

editor.getElement(options: GetElementOptions): SlateElement | null

Parameters

options
GetElementOptions
required
Configuration object for retrieving the element

Return Value

Returns the matching SlateElement or null if not found.

Examples

Basic Usage

// Get element by type and path
const item = editor.getElement({
  blockId: 'accordion-1',
  type: 'accordion-list-item',
  path: [0, 1]
});

if (item) {
  console.log('Item props:', item.props);
}

Get with Matcher

// Find active tab
const activeTab = editor.getElement({
  blockId: 'tabs-1',
  match: (el) => el.type === 'tabs-item-heading' && el.props?.active === true
});

// Find expanded accordion item
const expandedItem = editor.getElement({
  blockId: 'accordion-1',
  match: (el) => el.type === 'accordion-list-item' && el.props?.isExpanded
});

Get by Path

// Get item at specific path
const item = editor.getElement({
  blockId: 'accordion-1',
  type: 'accordion-list-item',
  path: [0, 0] // First item
});

// Get item at another path
const lastItem = editor.getElement({
  blockId: 'accordion-1',
  type: 'accordion-list-item',
  path: [0, 2] // Third item
});

Use Cases

Toggle Element State

const toggleAccordionItem = (blockId: string, itemPath: number[]) => {
  const item = editor.getElement({
    blockId,
    type: 'accordion-list-item',
    path: itemPath
  });

  if (item) {
    editor.updateElement({
      blockId,
      type: 'accordion-list-item',
      props: { isExpanded: !item.props?.isExpanded },
      path: itemPath
    });
  }
};

Check Element Properties

const isTabActive = (blockId: string, tabId: string): boolean => {
  const tab = editor.getElement({
    blockId,
    match: (el) => el.type === 'tabs-item-heading' && el.id === tabId
  });

  return tab?.props?.active === true;
};

Get Cell Properties

const getCellWidth = (blockId: string, cellPath: number[]): number | undefined => {
  const cell = editor.getElement({
    blockId,
    type: 'table-data-cell',
    path: cellPath
  });

  return cell?.props?.width as number | undefined;
};

Type Definition

type GetElementOptions = {
  blockId: string;
  type?: string;
  path?: number[];
  match?: (element: SlateElement) => boolean;
};

type SlateElement = {
  id?: string;
  type: string;
  props?: Record<string, unknown>;
  children: (SlateElement | SlateElementTextNode)[];
};