ContentEditable, execCommand, and forced selection of selected text

I am fooling myself with contentEditable and execCommand and I am trying to make it so that when the button is clicked

  • If the text selected in contentEditable becomes bold

  • If there is no text in contentEditable, then any text entered in contentEditable after clicking the button is in bold

I tried using the following Javascript command:

 document.execCommand('bold', false, null);

But, unfortunately, this only leads to the fact that the text is highlighted in bold; if no text is selected and you start to enter text after clicking the button, the text is displayed without opening.

I noticed that if I press Ctrl + B in contentEditable, it will do exactly what I would like to accomplish, but I would like to do it with Javascript (and without simulating Ctrl + B in Javascript).

+3
source share
2 answers

Actually the call document.execCommand()does exactly what you want (you can prove it by calling it from the event handler keydown), and I suspect that this is the action of any button or anything that you can use to run the command, which is the problem.

+2
source

Javascripts Range , . . (startnode, endnode, offset ..). , , <p>, css. , IE...

0

All Articles