DOM Selection

Quick introduction to the HTML DOM selection API.

A cheatsheet by @rstacruz|Refreshed 7 months ago.Refresh|View source on Github

Selection

Selection

var sel = document.getSelection()

See: https://devdocs.io/dom/selection

Methods

Methods

sel.removeAllRanges() //  deselects
sel.addRange(range) //    sets a selection
sel.removeRange(range) // remove a range
sel.rangeCount
sel.getRangeAt(0) // get the 0th range

Collapsing

Collapsing

sel.collapse(parent, offset)
sel.collapseToEnd()
sel.collapseToStart()
sel.isCollapsed
sel.containsNode(node)

Deleting

Deleting

sel.deleteFromDocument()

Events

Events

document.addEventListener('selectionchange', () => {})