0

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?

Community
  • 1
  • 1
lilHar
  • 1,735
  • 3
  • 21
  • 35
  • Are you saying that you want to get the html element that the selected text is in so that you can apply something to it? – ComputerLocus Jul 18 '16 at 21:32
  • Kind of. Getting the element it's in might include more than I want. So if I was going for a highlighted "the" in this sentence, I'd get the whole sentence, not just the the. – lilHar Jul 18 '16 at 21:37

2 Answers2

1

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/

Simon Kraus
  • 736
  • 4
  • 14
1

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

Community
  • 1
  • 1
eltonkamami
  • 5,134
  • 1
  • 22
  • 30