How to expand selection to include surrounding link tag?

690 views Asked by At

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

There are 2 answers

1
Gabriele Petrioli On BEST ANSWER

Try

  var selection = document.getSelection(), // get selection
      node = selection.anchorNode; // get containing 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
  }

Demo at http://codepen.io/gpetrioli/pen/lkrFi

1
Pradeep shyam On

try this,

var a = document.getElementsByTagName('a');

while(a.length) {
    var parent = a[ 0 ].parentNode;
    while( a[ 0 ].firstChild ) {
        parent.insertBefore(  a[ 0 ].firstChild, a[ 0 ] );
    }
     parent.removeChild( a[ 0 ] );
}