To answer your question about what alternatives there are, you could force the issue and set any a
element's href
attribute before calling unlink
:
$(document).ready(function() {
var $editable = $('[contenteditable]');
$('#btn').click(function() {
$editable.find('a:not([href])').attr('href', '#');
document.execCommand("unlink", false, false);
});
});
http://jsfiddle.net/Bz7pR/7/
There are, of course, probably multiple ways to "solve" the problem. I figure $.unwrap()
would probably work as well. I'm not that versed on document.execCommand
and rich text editors, but I imagine you need to be careful, precise, and test test test.
Note, that is just a demonstration; you've really got to think about that and consider exactly how you're going to handle that problem. For instance, you could detect and only run that if Firefox is the browser, which would limit any unexpected damage or outcomes you might have.
EDIT
And here is a more complete version that only affects the selected text range:
$(document).ready(function() {
$('#btn').click(function unlink() {
var holder,
frag,
range,
child;
if (window.getSelection && window.getSelection().getRangeAt) {
holder = document.createElement('div');
frag = document.createDocumentFragment();
range = window.getSelection().getRangeAt(0);
$(holder)
.append(range.cloneContents())
.find('a:not([href])')
.attr('href', '#');
while ((child = holder.firstChild)) {
frag.appendChild(child);
}
range.deleteContents();
range.insertNode(frag);
}
document.execCommand("unlink", false, false);
});
});
http://jsfiddle.net/Bz7pR/12/
I'm no genius when it comes to text ranges and selections, so I modified the code found in this answer:
https://stackoverflow.com/a/6252893/451969
To come up with what is above. If someone sees something that's either wrong or incoherent, leave me a comment below.