L
L
Lolo Penguin2020-05-08 12:22:52
JavaScript
Lolo Penguin, 2020-05-08 12:22:52

How to replace selected text with html code?

// выделенный текст
    sel = window.getSelection();

    // если выделена не пустота
    if (sel.rangeCount) {
        range = sel.getRangeAt(0);

        // удалит выделенный тект
        range.deleteContents();
        range.insertNode(document.createTextNode(replacementText));
    }


This will replace the selected text with text, but how do I replace the selected text with html? Those. I need to insert tags between the selected text, I suppose to replace the entire text with my own html, but if possible, I would insert tags between the text, such as surroundContents(), but this method is not suitable, because replaces parent tags and I need to insert new ones. thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lolo Penvin, 2020-05-08
@ledo02

document.execCommand('insertHTML', false, ' ' + document.getSelection().toString() + ' ');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question