这是我的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<div style="display: inline">测</div><div style="display: inline">试</div>
<br>
<div style="display: inline">测</div><div style="display: inline">试</div>
</div>
<input type="button" value="点我" onclick="f()">
<script>
function f(){
let a=window.getSelection();
for(let i=0;i<a.length;i++){
if(a[i].tagName==="DIV"){
a[i].style.color="red";
}
}
}
</script>
</body>
</html>
我希望a能是一个数组、包含选中范围内的所有节点,这样就可以使得点击按钮后、选中的所有文字都变成红色。
我知道我的a不是数组,我知道上面代码的语法是错的,但我不知道正确的语法是什么。所以我想问的是:如何让a是数组、包含选中范围内的所有节点?
(注:只考虑【被选中的所有节点都是同级的,不存在带有父节点与子节点的情况】且【每个节点只有一个字,不存在“选中这个节点中的部分文字”】的简单情形即可。)