Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execCommand on Range

I've been calling execCommand on the document to make the selected text bold or to set its color. But recently I need to use execCommand on a certain range and not the selected text.

Can I do this and if so how?

like image 911
Joshua Avatar asked Jul 02 '11 10:07

Joshua


People also ask

Is execCommand obsolete?

execCommand() Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.

Why is execCommand deprecated?

execCommand() is completely dead because some parts of it still work fine. Unfortunately the primary issue for me was that browsers use a lot of different code to generate those styles which are not recognized by screen readers used by those who are blind or nearly so.


1 Answers

You can, but it needs to be the selection. So in other words, do the following:

  • Store the current selection
  • Make a new selection based on the Range
  • Perform the execCommand
  • Restore the previous selection

You can create a selection from ranges (non-IE browsers) with the following:

 var selection = window.getSelection();
 selection.removeAllRanges();
 selection.addRange(range);

With IE, you can directly execute execCommand on TextRange objects, so this whole process won't be necessary.

like image 178
Niklas Avatar answered Oct 20 '22 00:10

Niklas