如何使用JavaScript从网页中删除链接?我正在使用Google Chrome.我试过的代码是:
function removehyperlinks() {
try {
alert(document.anchors.length);
alert(document.getElementsByTagName('a'));
for(i=0;i=document.anchors.length;i++) {
var a = document.anchors[i];
a.outerHTML = a.innerHTML;
var b = document.getElementsByTagName('a');
b[i].outerHTML = b[i].innerHTML;
}
} catch(e) { alert (e);}
alert('done');
}
Run Code Online (Sandbox Code Playgroud)
当然,这是测试代码,这就是为什么我同时尝试警报和两件事.第一个警报返回"0"第二个[Object NodeList],第三个返回"done".
我的html主体看起来像这样:
<body onload="removehyperlinks()">
<ol style="text-align:left;" class="messagelist">
<li class="accesscode"><a href="#">General information, Updates, & Meetings<span class="extnumber">141133#</span></a>
<ol>
<li><a href="#">...</a></li>
<li><a href="#">...</a></li>
<li><a href="#">...</a></li>
<li><a href="#">...</a></li>
<li><a href="#">...</a></li>
<li><a href="#">...</a></li>
<li><a href="#">...</a></li>
<li><a href="#">...</a></li>
<li start="77"><a href="#"">...</a></li>
<li start="88"><a href="#">...</a></li>
<li start="99"><a href="#">...</a></li>
</ol>
</li>
</ol>
</body>
Run Code Online (Sandbox Code Playgroud)
如果你可以包含jquery,你可以简单地使用
$('document').ready(function (){
$('a').contents().unwrap();
});?????????????????
Run Code Online (Sandbox Code Playgroud)
这里有一些香草JS可以解决问题.它所做的就是用a标签span和副本替换标签class和id属性(如果它们存在).
var anchors = document.getElementsByTagName("A");
for ( var i=0; i < anchors.length; i++ ) {
var span = document.createElement("SPAN");
if ( anchors[i].className ) {
span.className = anchors[i].className;
}
if ( anchors[i].id ) {
span.id = anchors[i].id;
}
span.innerHTML = anchors[i].innerHTML;
anchors[i].parentNode.replaceChild(span, anchors[i]);
}
Run Code Online (Sandbox Code Playgroud)
function removehyperlinks() {
try {
for(i=0;i<document.anchors.length;i++) {
document.anchors[i].outerHTML = document.anchors[i].innerHTML
}
} catch(e) { alert ("try2:" + e);}
}
function runner() {
for(i=1;document.anchors.length > 0;i++) {
//alert('run ' + i + ':' + document.anchors.length);
removehyperlinks();
}
}
Run Code Online (Sandbox Code Playgroud)
这有效。由于我可以控制内容,因此我使用简单的搜索和替换将所有锚点命名为“链接”。如果你运行一次,它就会淘汰所有其他的。所以我只是重复一遍,正如你所看到的,直到他们全部出局。