Skip to content

useHighlight

Highlights all occurrences of a search string within a target element using the CSS Custom Highlight API.

Browser support

This composable requires the CSS Custom Highlight API. It throws UnsupportedHighlightApiError in environments where CSS.highlights is unavailable.

Live examples

Reactive search highlight

Manual highlight trigger

Signature

ts
function useHighlight(
  target: MaybeComputedElementRef,
  search: MaybeRefOrGetter<string>,
  options?: UseHighlightOptions,
): {
  highlight: (queryInput?: MaybeRefOrGetter<string>) => void;
  clearHighlight: () => void;
  matchCount: Ref<number>;
};

Parameters

ParameterTypeDescription
targetMaybeComputedElementRefTarget element or component ref.
searchMaybeRefOrGetter<string>The string to search and highlight.
optionsUseHighlightOptionsOptional configuration (see below).

Options

OptionTypeDefaultDescription
excludeMaybeRefOrGetter<string[]>[]CSS selectors — text nodes under matching ancestors are skipped.
cssHighlightKeystring"search-results"Key used in CSS.highlights. Must match the ::highlight() CSS pseudo-element.
manualbooleanfalseWhen true, disables the automatic watcher — call highlight() yourself.
immediatebooleantrueWhen false, the watcher does not run on initial mount.

Return value

PropertyTypeDescription
highlight(query?) => voidManually trigger highlighting. Accepts an optional query override.
clearHighlight() => voidRemove highlights and reset matchCount to 0.
matchCountRef<number>Reactive count of current matches.