Skip to content
Advertisement

Remove links with JavaScript in browser

How do I remove links from a webpage with JavaScript? I am using Google Chrome. The code I tried is:

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

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:

<body onload="removehyperlinks()">
<ol style="text-align:left;" class="messagelist">
    <li class="accesscode"><a href="#">General information, Updates, &amp;   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>

Advertisement

Answer

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

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement