Selection.addRange()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.

概述

向选区(Selection)中添加一个区域(Range)。

语法

sel.addRange(range)

参数

range

一个区域(Range)对象将被增加到选区(Selection)当中。

例子

js
/* 在一个 HTML 文档中选中所有加粗的文本。 */

var strongs = document.getElementsByTagName("strong");
var s = window.getSelection();

if (s.rangeCount > 0) s.removeAllRanges();

for (var i = 0; i < strongs.length; i++) {
  var range = document.createRange();
  range.selectNode(strongs[i]);
  s.addRange(range);
}

规范

Specification
Selection API
# dom-selection-addrange

浏览器兼容性

BCD tables only load in the browser

相关链接