Javascript: how to change the range of un-surroundContents

This function uses a range object to return the user's selection and wrap it with a bold tag. is there a method that allows me to remove tags? Like in <b>text<b>= text.


I really need a toggle function that wraps the selection with tags and wraps it if it already contains tags. Like text editors when you switch bold.

if "text" then "<b>text</b>"
else "<b>text</b>" then "text"  

...

function makeBold() {

    //create variable from selection
    var selection = window.getSelection();
        if (selection.rangeCount) {
        var range = selection.getRangeAt(0).cloneRange();
        var newNode = document.createElement("b");

            //wrap selection in tags
        range.surroundContents(newNode);

            //return the user selection
        selection.removeAllRanges();
        selection.addRange(range);
    } 
}
+3
source share
1 answer

, , , (.. /) , (<strong> versus <bold> , , <span style="font-weight: bold">), document.execCommand(), :

function toggleBold() {
    document.execCommand("bold", false, null);
}

, , IE. , , :

function toggleBold() {
    var range, sel;
    if (window.getSelection) {
        // Non-IE case
        sel = window.getSelection();
        if (sel.getRangeAt) {
            range = sel.getRangeAt(0);
        }
        document.designMode = "on";
        if (range) {
            sel.removeAllRanges();
            sel.addRange(range);
        }
        document.execCommand("bold", false, null);
        document.designMode = "off";
    } else if (document.selection && document.selection.createRange &&
            document.selection.type != "None") {
        // IE case
        range = document.selection.createRange();
        range.execCommand("bold", false, null);
    }
}
+5

Source: https://habr.com/ru/post/1781038/


All Articles