How do I remove links from a webpage with JavaScript? I am using Google Chrome. The code I tried is:
JavaScript
x
14
14
1
function removehyperlinks() {
2
try {
3
alert(document.anchors.length);
4
alert(document.getElementsByTagName('a'));
5
for(i=0;i=document.anchors.length;i++) {
6
var a = document.anchors[i];
7
a.outerHTML = a.innerHTML;
8
var b = document.getElementsByTagName('a');
9
b[i].outerHTML = b[i].innerHTML;
10
}
11
} catch(e) { alert (e);}
12
alert('done');
13
}
14
Of course, this is test code, which is why I have the alerts and 2 things trying at the same time. The first alert returns “0” the second [Object NodeList] and the third returns “done”.
My html body looks like this:
JavaScript
1
20
20
1
<body onload="removehyperlinks()">
2
<ol style="text-align:left;" class="messagelist">
3
<li class="accesscode"><a href="#">General information, Updates, & Meetings<span class="extnumber">141133#</span></a>
4
<ol>
5
<li><a href="#"></a></li>
6
<li><a href="#"></a></li>
7
<li><a href="#"></a></li>
8
<li><a href="#"></a></li>
9
<li><a href="#"></a></li>
10
<li><a href="#"></a></li>
11
<li><a href="#"></a></li>
12
<li><a href="#"></a></li>
13
<li start="77"><a href="#"">...</a></li>
14
<li start="88"><a href="#"></a></li>
15
<li start="99"><a href="#"></a></li>
16
</ol>
17
</li>
18
</ol>
19
</body>
20
Advertisement
Answer
JavaScript
1
14
14
1
function removehyperlinks() {
2
try {
3
for(i=0;i<document.anchors.length;i++) {
4
document.anchors[i].outerHTML = document.anchors[i].innerHTML
5
}
6
} catch(e) { alert ("try2:" + e);}
7
}
8
function runner() {
9
for(i=1;document.anchors.length > 0;i++) {
10
//alert('run ' + i + ':' + document.anchors.length);
11
removehyperlinks();
12
}
13
}
14
This works. As I am in control of the content, I named all the anchors “link” using a simple search and replace. If you run it once, it takes out every other one. So I just had it repeat, as you can see, till they are all out.