Javascript selected text highlighting prob

后端 未结 6 693
名媛妹妹
名媛妹妹 2021-01-31 05:14

I have a html page with text content. On selecting any text and pressing the highlight button, I can change the style of the selected text to highlight the same. To implement th

6条回答
  •  感动是毒
    2021-01-31 05:22

    See Range.extractContents:

    document.getElementById('execute').addEventListener('click', function() {
        var range = window.getSelection().getRangeAt(0),
            span = document.createElement('span');
    
        span.className = 'highlight';
        span.appendChild(range.extractContents());
        range.insertNode(span);
    });
    .highlight { background-color: yellow; }
    Select any part of this text and then click 'Run'.

提交回复
热议问题