Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulate highlighted text with Javascript

HI, I'm trying to develop some code in Javascript that adds highlighted text to a class. What I want to achieve with this is the ability of text highlighting with a custom color.

I want it to kind of look like the following:

window.getSelected = "<span class=\"highlighted\">" + window.getSelected + "</span>"

after the above code is executed the selected text's background is surrounded by span tags.

thanks,

fbr

like image 303
ForeignerBR Avatar asked Nov 15 '22 11:11

ForeignerBR


1 Answers

You'll want to look into Range Objects, there is a good summary here:

http://www.quirksmode.org/dom/range_intro.html

Browser compatibility will be an issue, but basically, you can get the current selection in the way you suggest, then convert it into a Range, and use the methods of the Range object to find and split the existing DOM nodes, and insert your own <span> tag containing the selected text.

It's not entirely trivial, and involves getting into serious DOM manipulation, but it's a rewarding subject to get your head around. Enjoy!

like image 52
beeglebug Avatar answered Dec 09 '22 17:12

beeglebug