JavaScript | Range | Selection - Is there a way to "unbold", "unitalic" a contenteditable with Range and Selection with Javascript?

Viewed 204

Hey guys! I'm starting my first ReactJs Project and I'm trying to create a contenteditable component that handles "bold" and "italic" when making a selection and pressing a button, here's my code for that:

bold = ( e ) => {
  e.preventDefault();
  const selection = window.getSelection();
  if( !selection.isCollapsed ){
    const range = selection.getRangeAt(0);
    const b = document.createElement('b');
    b.appendChild(range.extractContents());
    range.insertNode(b);
    this.setState({html: this.contentEditable.current.innerHTML})
  }
}

italic = ( e ) => {
  e.preventDefault();
  const selection = window.getSelection();
  if (!selection.isCollapsed){
    const range = selection.getRangeAt(0);
    const i = document.createElement('i');
    i.appendChild(range.extractContents());
    range.insertNode(i);
    this.setState({html: this.contentEditable.current.innerHTML})
  }
}

render () {
  return (
    <div>
      <ContentEditable html={this.state.html} />
      <button onClick={this.bold}>bold</button>
      <button onClick={this.italic}>italic</button>
    </div>
  )
}

Even if I make a selection from a half of a <i> tag and make it bold it works fine, since I'm extracting the range contents and appending it to a new node.

The problem now is: Is there a way to "unbold" or "unitalic" a piece of text as the following example?

Before:

<b>I am <i>selecting some piece of text</b> to change the</i> tags position

After:

<b>I am <i>selecting some</b></i> piece of <i><b>text</b> to change the</i> tags position

I could really use someone's help in this situation!

0 Answers
Related