Skip to content Skip to sidebar Skip to footer

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

Solution 1:

If you can include jquery, you can do it simply with

$('document').ready(function (){
    $('a').contents().unwrap();
});​​​​​​​​​​​​​​​​​

Solution 2:

Here's some vanilla JS that does the trick. All it does is replace a tags with span's and copies over class and id attributes (if they exist).

var anchors = document.querySelectorAll("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]);
}

Solution 3:

You can use removeAttribute:

var allImages = document.querySelectorAll('.imageLinks');

functionremovehyperlinks()(){  
    for (var i = 0; i < allImages.length; i++) {
    allImages[i].removeAttribute("href");
  }
}

removehyperlinks()()

Solution 4:

Try

var ary = document.getElementsByTagName("a");

to get the anchors.

Then you can remove them like this

for (var i=0;i<ary.length;i++) {
  // brain cramp: document.removeElement(ary[i]);
  ary[i].parentNode.removeChild(ary[i]);
}

Solution 5:

functionremovehyperlinks() {
    try {
        for(i=0;i<document.anchors.length;i++) {
            document.anchors[i].outerHTML = document.anchors[i].innerHTML
        }
    } catch(e) { alert ("try2:" + e);}
}
functionrunner() {
    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.

Post a Comment for "Remove Links With Javascript In Browser"