Dhaval Varsada
Dhaval Varsada

Reputation: 91

How to wrap and unwrap selected text in contenteditable div?

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.

Upvotes: 1

Views: 2558

Answers (3)

Macedo_Montalvão
Macedo_Montalvão

Reputation: 579

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();

Upvotes: 0

Tony
Tony

Reputation: 7445

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.

Upvotes: 1

RustyToms
RustyToms

Reputation: 7810

jQuery will save you much trouble here:

jQuery wrap docs

jQuery unwrap() docs

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

Upvotes: 1

Related Questions