大网数据广告活动
Web 标准与前端开发

Selection: empty() method

· 52CE 我爱测

The **`Selection.empty()`** method removes all ranges from the selection, leaving the Selection.anchorNode and Selection.focusNode properties equal to `null` and nothing selected. When this method is called, a Document/selectionchange_event event is fired at the document.

DOM

The Selection.empty() method removes all ranges from the selection, leaving the Selection.anchorNode and Selection.focusNode properties equal to null and nothing selected. When this method is called, a Document/selectionchange_event event is fired at the document.

[!NOTE] This method is an alias for the Selection.removeAllRanges() method.

Syntax

empty()

Parameters

None.

Return value

None (undefined).

Examples

This example displays a message when something is selected on the page or not. It does this by listening to the Document/selectionchange_event event on the document. There also is a button that clears any selection by calling Selection.empty(). When this happens, the selection is changed and the message is updated.

<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse laoreet
  urna eget sapien venenatis, eget facilisis diam mattis.
</p>
<button>Clear selection</button>
<pre id="log"></pre>
const log = document.getElementById("log");

// The selection object is a singleton associated with the document
const selection = document.getSelection();

// Logs if there is a selection or not
function newSelectionHandler() {
  if (selection.rangeCount !== 0) {
    log.textContent = "Some text is selected.";
  } else {
    log.textContent = "No selection on this document.";
  }
}

document.addEventListener("selectionchange", () => {
  newSelectionHandler();
});

newSelectionHandler();

// The button cancel all selection ranges
const button = document.querySelector("button");
button.addEventListener("click", () => {
  selection.empty();
});

Examples

Specifications

Browser compatibility

See also

  • Selection.removeAllRanges()
  • Document/selectionchange_event

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。