如何展开选择以包括周围的链接标记
How to expand selection to include surrounding link tag?
我有一个可编辑的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 ] );
}
相关文章:
- 如何将页面上的所有电话号码更改为可点击链接,不包括特定类别的元素
- 蛋糕PHP电子邮件 - 包括电子邮件中的链接
- 如何展开选择以包括周围的链接标记
- 当满足javascript/jquery条件时显示DIV(包括jsFiddle链接)
- 如何根据此方法跟踪Google Analytics中的出站链接,包括.标签和非交互
- 有没有一种方法可以包括<脚本>或者<link>在所有页面中显示一次
- 包括& # 39;我# 39;Node.js中的between链接
- 为网站添加整体平滑滚动(不包括同一页面中的锚链接)
- 如何使用adobeillustrator生成的SVG,包括位图图像作为链接与onclick
- 用正则表达式标记字符串中的文本,但不包括链接
- 使用AngularJS/Javascript禁用仅浏览器返回按钮导航(不包括应用中的链接)
- 链接3个简单的正方形数据,其中包括所需的颜色
- Jquery /javascript代码,用于获取网页主页面的全文内容(包括链接文本但不包括图像)
- Ember js链接模板包括
- Javascript或jquery代码获得整个文本内容的网页内的iframe(包括/不包括该页面的链接)
- 完全禁用一个元素,包括在点击动作时调用其他javascript函数的链接
- 我知道如何改变文本使用javascript (getElementById),但我如何使该文本包括eg.链接
- 如何确定用户何时离开网页(不包括某些链接)
- 如何包括/添加/链接第二个脚本标签到第一个脚本标签
- 对彼此链接的多行进行排序(包括小提琴示例)