A
A
Alexander Nevsky2019-06-05 11:42:05
JavaScript
Alexander Nevsky, 2019-06-05 11:42:05

WYSIWYG editor. How to properly wrap selected text in a block?

I am making a text editor for my website. I don't want to use third parties.
The editor is based on the contenteditable property.
I need to wrap the selected text in a div with the dialog class when the button is clicked. But at the same time, so that on the SECOND click with the same area selected, this div would be removed, and "document.execCommand(undo, false, null)" would also work.
I'm thinking of doing something like this "document.execCommand('insertHTML', false, div)", but there is a problem in the div, you need to push a line with the code of the selected text wrapped in a div with a class.
Wanted to do this, but the div variable is an object.

var range = window.getSelection().getRangeAt(0),
selectionContents = range.extractContents(),
div = document.createElement('div');

div.appendChild(selectionContents);
div.setAttribute('class', 'dialog');
document.execCommand('insertHTML', false, div);

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question