Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript selected text highlighting prob

Tags:

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)?

like image 640
dev_android Avatar asked Apr 27 '15 11:04

dev_android


People also ask

How do I highlight selected text in JavaScript?

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.

How do you highlight text in a different Colour in HTML?

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.

What is window getSelection?

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.


1 Answers

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>
like image 182
André Dion Avatar answered Sep 22 '22 02:09

André Dion