I'm wrapping the selected text in span tags, when you click a button. If I then select a different piece of text and click the button, that text also gets wrapped in tags. However, when I select a piece of text that's already wrapped in span tags, I'd like to remove those tags to unembolden the text, instead of wrapping those tags in more tags.
HTML
<div contenteditable="true" class="textEditor">Some random text.</div>
<a href="#" class="embolden">Bold</a>
JS
$('.embolden').click(function(){
var highlight = window.getSelection();
var span = '<span class="bold">' + highlight + '</span>';
var text = $('.textEditor').html();
$('.textEditor').html(text.replace(highlight, span));
});
JSFiddle Demo
I'm probably getting greedy with this request but I select just part of a piece of text that's already wrapped in span tags, but not all of it, I'd like to close the original tag at the start of the selection, open a new tag right after that, then close the new tag at the end of the selection and open a new tag after that.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…