'surroundContents on multiple ranges in an element, without affecting each other

I am trying to wrap some ranges by the span tag, like below:

document.body.innerHTML=`123`

function newRange(start,end){
    let range = document.createRange();
    let startNode=document.body.firstChild
    let endNode=document.body.firstChild
    range.setStart(startNode, start);
    range.setEnd(endNode, end);
    return range
}

function wrapRange(range){
    const parent = document.createElement('span');
    range.surroundContents(parent);
}

let range1=newRange(0,1)
let range2=newRange(1,2)
wrapRange(range1)
wrapRange(range2)
console.log(document.body.innerHTML)

The output that I expect is <span>1</span><span>2</span>3

However, the acutal output is <span><span>1</span>2</span>3

It seems the previous surroundContents operation will affect the content of other ranges.

How to avoid that?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source