How to wrap and unwrap selected text in contenteditable div?

2.4k views Asked by At

JSFIDDLE DEMO

JsFiddle Demo completely work for wrap text but i'm not know how it is unwrap selected text.

 range.text = '[' + tag + ']' + selectedText + '[/' + tag + ']';

how is it unwrap tag and get original selected text.

3

There are 3 answers

2
RustyToms On

jQuery will save you much trouble here:

jQuery wrap docs

jQuery unwrap() docs

$('findyourtaghere').contents().unwrap();

0
Tony On

If you don't want to use jQuery, you can use something like this:

var element = document.createElement('span');
element.originalText = selectedText;
element.textContent = '[' + tag + ']' + selectedText + '[/' + tag + ']';
element.onclick = function() {
    this.parentNode.replaceChild(document.createTextNode(this.originalText), this);  
};
range.insertNode(element);

I used span element here, not textNode, it's easy to use for your purposes. But you need to take care of browser compatibility.

0
Macedo_Montalvão On

I still haven't found what I was looking for, but I found the solution for what you're looking for, this single line will take the parent element of the selected text and remove it keeping the text where it is, unless you select something other than text like an element for example, but then it would be another problem.

$(window.getSelection().anchorNode.parentElement).unwrap();