Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

copyElementText

Copies the text content of a DOM element to the clipboard.

TypeScript
Copied!
1/**
2 * Copies the text content of a DOM element to the clipboard.
3 *
4 * @param element - The DOM element whose text content should be copied.
5 * @returns A promise that resolves when the text is successfully copied.
6 */
7export async function copyElementText(element: HTMLElement): Promise<void> {
8  const text = element.innerText || element.textContent || '';
9  await navigator.clipboard.writeText(text);
10}
  • Direct Element Integration

    Eliminates the need to manually extract text; seamlessly works with any text-containing DOM element.

  • Leverages Modern Clipboard API

    Uses navigator.clipboard.writeText for secure, reliable, and asynchronous clipboard interaction.

  • Fallback-Safe Text Extraction

    Safely accesses both innerText and textContent, ensuring maximum compatibility across element types.

  • Concise and Focused

    Purpose-built for a single, common interaction — copying visible or hidden textual content.

Tests | Examples

TypeScript
Copied!
1test('copyElementText - copies text content of an element', async () => {
2  const mockWriteText = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue();
3  const div = document.createElement('div');
4  div.textContent = 'Copy this text';
5
6  await copyElementText(div);
7
8  expect(mockWriteText).toHaveBeenCalledWith('Copy this text');
9
10  mockWriteText.mockRestore();
11});
12
13test('copyElementText - falls back to innerText if available', async () => {
14  const mockWriteText = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue();
15  const div = document.createElement('div');
16  Object.defineProperty(div, 'innerText', {
17    get: () => 'Text from innerText',
18  });
19
20  await copyElementText(div);
21
22  expect(mockWriteText).toHaveBeenCalledWith('Text from innerText');
23
24  mockWriteText.mockRestore();
25});

Common Use Cases

  • Copy Buttons in UI

    Add "Copy" functionality for code snippets, contact info, or shareable links on webpages.

  • Clipboard Utilities in Forms

    Let users copy generated passwords, verification codes, or summaries from form components.

  • Tooltips and Notifications

    Integrate into tooltips/popovers where copying content is part of the UX.

  • Documentation and Examples

    Enable copying example blocks from guides, markdown previews, or sandbox environments.

  • Accessibility Enhancements

    Provide non-keyboard users a simple way to copy content without manual text selection.

Codebase: Utilities -> Browser & DOM -> copyElementText | Yevhen Klymentiev