Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unwrap selected text from html tag using pure js

I'm working on a simple text editor using contenteditable in javascript. Unfortunately, I cannot use document.execCommand and have to implement it myself. I have created a function that makes my text bold. Here is the function:

document.getElementById("bold").onclick = function() {
  var selection = document.getSelection(),
      range = selection.getRangeAt(0).cloneRange();
  range.surroundContents(document.createElement("b"));
  selection.removeAllRanges();
  selection.addRange(range);
}
<div id="editor" contenteditable="true">This is the contenteditable</div>
<button id="bold">Bold</button>

Now, when the user clicks on the bold button when the text is already bold, I want to unembolden the text. In other words, i want the text to not be bold anymore.

How can i do this? Is there like any opposite of range.surroundContents or something like that?

Note that I would like only the selected text to unbold and not every bold text in the document so jQuery's unwrap() will probably not work. I'm looking for a Vanilla js solution and something that's elegant and simple, but if it has to be complicated, I would appreciate some explanation of the code. Thank you very much.

like image 965
Yang K Avatar asked Dec 11 '25 11:12

Yang K


1 Answers

Stash the created element:

let b = document.createElement("b");
range.surroundContents(b);

To unwrap, move each of the children to just before the b element, and then delete the b element:

while (b.firstChild) {
    b.parentNode.insertBefore(b.firstChild, b)
}

b.parentNode.removeChild(b)
like image 197
nathancahill Avatar answered Dec 13 '25 01:12

nathancahill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!