lilHar
lilHar

Reputation: 1866

Get highlighted text as a node in javascript

Working on a bit of javascript code; I'm wanting to alter the text when highlighted. The closest I've found currently is this: Get The Highlighted Selected Text. The problem with that solution though is it just gets the text that's highlighted as a string, but it's as a string. So I have the text, but I can't edit it like a node, doing innerHTML, change font, etc. It's just a string. I've got a solution that "works"™, but what is, is taking that string, and then searching for it. The problem is, if for example I highlight the string "the" in this post, I'd get a whole bunch of answers and no way to differentiate between them.

Is there a way to get selected text as a node?

Upvotes: 0

Views: 676

Answers (2)

eltonkamami
eltonkamami

Reputation: 5190

You can get an idea of how its done from this answer https://stackoverflow.com/a/3997896/5267669

Basically you get the selected text with the document.getSelection method, you delete it and in its place you insert your own content.

For example replace your selection with an H1 tag containing the text Added with js

sel = window.getSelection();
if (sel.rangeCount) {
   range = sel.getRangeAt(0);
   range.deleteContents();
   var h1 = document.createElement("h1");
   h1.textContent = 'Added with js';
   range.insertNode(h1);
}

You can select anything on this page, paste this code to the console and the selection will be replaced with an h1 tag

Upvotes: 1

Simon Kraus
Simon Kraus

Reputation: 736

You need to look for the selection (window.getSelection();)and get its range to have the right position of the selected text. Then you can apply styles by span-wrapping. Take a look at

http://jsfiddle.net/jme11/bZb7V/

Upvotes: 1

Related Questions