Skip to main content

DOM

The @wordpress/dom package provides a comprehensive set of utilities for working with the DOM in WordPress. It includes functions for selection management, element manipulation, focus handling, and HTML sanitization.

Installation

You can install the package using npm:
npm install @wordpress/dom --save

Selection Utilities

documentHasSelection( doc )

Checks whether the current document has a selection, including focus in input fields, textareas, and general rich-text selection.
doc
Document
required
The document to check.
return
boolean
True if there is selection, false if not.
import { documentHasSelection } from '@wordpress/dom';

if ( documentHasSelection( document ) ) {
	console.log( 'Document has active selection' );
}

documentHasTextSelection( doc )

Checks whether the current document has selected text. This applies to ranges of text in the document, not selection inside <input> and <textarea> elements.
doc
Document
required
The document to check.
return
boolean
True if there is text selection, false if not.

documentHasUncollapsedSelection( doc )

Checks whether the current document has any sort of uncollapsed selection, including ranges of text and any selection inside textual inputs.
doc
Document
required
The document to check.
return
boolean
Whether there is any recognizable text selection in the document.

isEntirelySelected( element )

Checks whether the contents of the element have been entirely selected.
element
HTMLElement
required
The element to check.
return
boolean
True if entirely selected, false if not.

isSelectionForward( selection )

Returns true if the given selection object is in the forward direction.
selection
Selection
required
Selection object to check.
return
boolean
Whether the selection is forward.

Caret Positioning

computeCaretRect( win )

Gets the rectangle for the selection in a container.
win
Window
required
The window of the selection.
return
DOMRect | null
The rectangle.

getRectangleFromRange( range )

Gets the rectangle of a given Range. Returns null if no suitable rectangle can be found. Use this instead of Range.getBoundingClientRect(), which is often broken for collapsed ranges.
range
Range
required
The range.
return
DOMRect | null
The rectangle.

placeCaretAtHorizontalEdge( container, isReverse )

Places the caret at start or end of a given element.
container
HTMLElement
required
Focusable element.
isReverse
boolean
required
True for end, false for start.
import { placeCaretAtHorizontalEdge } from '@wordpress/dom';

// Place caret at the end of the element
placeCaretAtHorizontalEdge( element, true );

placeCaretAtVerticalEdge( container, isReverse, rect )

Places the caret at the top or bottom of a given element.
container
HTMLElement
required
Focusable element.
isReverse
boolean
required
True for bottom, false for top.
rect
DOMRect
The rectangle to position the caret with.

Edge Detection

isHorizontalEdge( container, isReverse )

Checks whether the selection is horizontally at the edge of the container.
container
HTMLElement
required
Focusable element.
isReverse
boolean
required
Set to true to check left, false for right.
return
boolean
True if at the horizontal edge, false if not.

isVerticalEdge( container, isReverse )

Checks whether the selection is vertically at the edge of the container.
container
HTMLElement
required
Focusable element.
isReverse
boolean
required
Set to true to check top, false for bottom.
return
boolean
True if at the vertical edge, false if not.

Element Type Detection

isFormElement( element )

Detects if element is a form element.
element
Element
required
The element to check.
return
boolean
True if form element, false otherwise.

isTextField( node )

Checks whether the given element is a text field, where text field is defined by the ability to select within the input, or that it is contenteditable.
node
Node
required
The HTML element.
return
boolean
True if the element is a text field, false if not.
import { isTextField } from '@wordpress/dom';

if ( isTextField( event.target ) ) {
	console.log( 'User is typing in a text field' );
}

isNumberInput( node )

Checks whether the given element is an input field of type number.
node
Node
required
The HTML node.
return
boolean
True if the node is number input.

Content Type Utilities

isPhrasingContent( node )

Finds out whether or not the given node is phrasing content.
node
Node
required
The node to test.
return
boolean
True if phrasing content, false if not.
See MDN: Phrasing content for more information.

isTextContent( node )

Checks if a node is text content.
node
Node
required
The node to check.
return
boolean
Whether the node is text content.

getPhrasingContentSchema( context )

Gets schema of possible paths for phrasing content.
context
string
Set to “paste” to exclude invisible elements and sensitive data.
return
object
Schema object.

Element Manipulation

insertAfter( newNode, referenceNode )

Inserts a node in the DOM as the next sibling of another node.
newNode
Node
required
Node to be inserted.
referenceNode
Node
required
Node after which to perform the insertion.
import { insertAfter } from '@wordpress/dom';

const newElement = document.createElement( 'div' );
insertAfter( newElement, referenceElement );

remove( node )

Removes a node from the DOM.
node
Node
required
Node to be removed.

replace( processedNode, newNode )

Replaces one DOM node with another.
processedNode
Element
required
Node to be removed.
newNode
Element
required
Node to be inserted in its place.

replaceTag( node, tagName )

Replaces a node with a new node with the given tag name.
node
Element
required
The node to replace.
tagName
string
required
The new tag name.
return
Element
The new node.

wrap( newNode, referenceNode )

Wraps a node with a new node with the given tag name.
newNode
Element
required
The node to insert.
referenceNode
Element
required
The node to wrap.

unwrap( node )

Unwraps the given node, moving any child nodes to the parent.
node
Node
required
The node to unwrap.
import { unwrap } from '@wordpress/dom';

// <div><span>Hello</span></div>
// After unwrap(span):
// <div>Hello</div>
unwrap( spanElement );

isEmpty( element )

Recursively checks if an element is empty. An element is not empty if it contains text or elements with attributes such as images.
element
Element
required
The element to check.
return
boolean
Whether or not the element is empty.

Layout Utilities

getOffsetParent( node )

Returns the closest positioned element, or null under any of the conditions of the offsetParent specification. Unlike offsetParent, this function accepts any Node (e.g., Node.TEXT_NODE).
node
Node
required
Node from which to find offset parent.
return
Node | null
Offset parent.

getScrollContainer( node, direction )

Finds the closest scrollable container node or the node itself, if scrollable.
node
Element | null
required
Node from which to start.
direction
string
default:"vertical"
Direction of scrollable container to search for (‘vertical’, ‘horizontal’, ‘all’).
return
Element | undefined
Scrollable container node, if found.
import { getScrollContainer } from '@wordpress/dom';

const scrollParent = getScrollContainer( element, 'vertical' );
if ( scrollParent ) {
	scrollParent.scrollTop = 0;
}

isRTL( element )

Checks whether the element’s text direction is right-to-left.
element
Element
required
The element to check.
return
boolean
True if rtl, false if ltr.

HTML Sanitization

safeHTML( html )

Strips scripts and on* attributes from HTML.
html
string
required
HTML to sanitize.
return
string
The sanitized HTML.
import { safeHTML } from '@wordpress/dom';

const unsafe = '<div onclick="alert(1)">Click me</div>';
const safe = safeHTML( unsafe );
// Result: '<div>Click me</div>'

removeInvalidHTML( HTML, schema, inline )

Cleans up HTML by removing or unwrapping nodes, attributes, and classes based on a schema.
HTML
string
required
The HTML to clean up.
schema
object
required
Schema for the HTML.
inline
boolean
required
Whether to clean for inline mode.
return
string
The cleaned up HTML.

File Handling

getFilesFromDataTransfer( dataTransfer )

Gets all files from a DataTransfer object.
dataTransfer
DataTransfer
required
DataTransfer object to inspect.
return
File[]
An array containing all files.
import { getFilesFromDataTransfer } from '@wordpress/dom';

element.addEventListener( 'drop', ( event ) => {
	const files = getFilesFromDataTransfer( event.dataTransfer );
	console.log( `Dropped ${files.length} files` );
} );

Focus Management

focus

Object grouping focusable and tabbable utilities under the keys with the same name.
import { focus } from '@wordpress/dom';

// Find all focusable elements
const focusableElements = focus.focusable.find( container );

// Find all tabbable elements
const tabbableElements = focus.tabbable.find( container );
Focusable elements are elements that can receive focus, while tabbable elements are focusable elements that can be reached using the Tab key.

Complete Example

import { 
	documentHasSelection, 
	placeCaretAtHorizontalEdge 
} from '@wordpress/dom';

function handleKeyDown( event ) {
	const { target, keyCode } = event;
	
	if ( keyCode === 37 ) { // Left arrow
		if ( ! documentHasSelection( document ) ) {
			// Move to previous block
			const previousBlock = getPreviousBlock();
			if ( previousBlock ) {
				placeCaretAtHorizontalEdge( previousBlock, true );
			}
		}
	}
}

Version

Current version: 4.40.0

Build docs developers (and LLMs) love