I have an editable div that contains the html:
"hello "<a href='#'>this is the title</a>" goodbye"
If I select just 'his is' part of the html of the link, and run:
document.execCommand('unlink');
The tag is broken into two tags leaving:
<a href='#'>t</a>"his is"<a href='#'>the title</a>
Is there a way to modify the selection to expand to the whole link tag to remove the whole link?
selection = document.getSelection() ?
UPDATE
Thanks to Gaby! I took his solution and modified it a bit to extend past interchanging bold and italic tags:
var selection = document.getSelection(); // get selection
var node = selection.anchorNode; // get containing node
var baseChild = function(parent, last) {
var children = parent.childNodes.length;
if (children == 0) {
return parent;
}
var child = (last == true) ? children-1 : 0;
return baseChild( parent.childNodes(child));
}
var findAndRemove = function(node) {
while (node && node.nodeName !== 'A'){ // find closest link - might be self
node = node.parentNode;
}
if (node){ // if link found
var range = document.createRange(); //create a new range
range.selectNodeContents(node); // set range to content of link
selection.addRange(range); // change the selection to the link
document.execCommand('unlink'); // unlink it
if ( node.previousSibling ){
findAndRemove(baseChild(node.previousSibling, true));
}
if ( node.nextSibling ){
findAndRemove(baseChild(node.nextSibling, false ));
}
}
}
findAndRemove(node);
Try
Demo at http://codepen.io/gpetrioli/pen/lkrFi