简体   繁体   中英

Remove Html tag from selected text with JavaScript

I am new at JavaScript and I tried to add a new tag to the selected word.
I did it like this:

function addBoldTag() {
                 var highlight = window.getSelection();
               if(highlight.toString().length>=1){
               var range = highlight.getRangeAt(0); 
                var selectionContents = range.extractContents(); 
                 var boldtag = document.createElement("b"); 
                 boldtag.style.cssText = " color :blue; ";
                 boldtag.appendChild(selectionContents); 
                 range.insertNode(boldtag); 
                 highlight.removeAllRanges(); 
                 }
}

I have a new issue now, I'd like to unwrap or remove selected word's tag, the way HTMLeditors does it, but I can't find a way to do it. I've found Jquery , but I have to do with pure javascript .

Please have a look below:

 const selectedRange = window.getSelection().getRangeAt(0); const element = document.createElement('strong'); selectedRange.surroundContents(element);

I hope it would help you out

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM