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 this feature, i have written the following method.
sel = window.getSelection(); var range = sel.getRangeAt(0); var span = document.createElement('span'); span.className = "highlight" + color; range.surroundContents(span);
This is working fine if you choose a text with no html tag, but when the text has any html tag in between, it is giving error
Failed to execute 'surroundContents' on 'Range': The Range has partially selected a non-Text node.
How to solve this problem. Is it possible to highlight the same separately for each part(divided by html tags)?
getSelection() Method in JavaScript. The window. getSelection() method in JavaScript allows us to get the text highlighted or selected by the user on the screen. This method returns an object that contains information related to the text highlighted on the screen.
The HTML <mark> element is found within the <body> tag. Most browsers will render the <mark> tag with a yellow background color but you can change this behavior with CSS. The <mark> tag defines text that has relevance and is not intended to be used to merely apply highlighter styling.
getSelection() The Window. getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret.
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; }
<div id="test"> Select any part of <b>this text and</b> then click 'Run'. </div> <button id="execute">Run</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With