如何展开选择以包括周围的链接标记

How to expand selection to include surrounding link tag?

本文关键字:链接 包括周 何展开 选择      更新时间:2023-09-26

我有一个可编辑的div,其中包含html:

"hello "<a href='#'>this is the title</a>" goodbye"

如果我只选择链接html的"his-is"部分,并运行:

document.execCommand('unlink');

标签被分解为两个标签离开:

<a href='#'>t</a>"his is"<a href='#'>the title</a>

有没有一种方法可以修改选择以扩展到整个链接标签以删除整个链接?

selection = document.getSelection() ?

更新

感谢Gaby!我接受了他的解决方案,并对其进行了一些修改,以扩展过去的粗体和斜体标签:

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

尝试

  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
  }

演示http://codepen.io/gpetrioli/pen/lkrFi

试试这个,

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 ] );
}
相关文章: