Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable all target="_blank" links on page

I'm building content for a site that is displayed through an iframe in a PhoneGap mobile app. The content is pulled from a CMS that also serves the content for the main website so it has a mix of internal and target="_blank" links.

Handling target="_blank" links is proving problematic in PhoneGap so I want to disable them in the app website without touching the content because it's also used on the main website.

What I need is jQuery that runs on page load, finds all links with target="_blank" attribute and makes links normal text.

Something like this (How to disable all links before load jQuery?) disables all links but I only want to disable links that have target="_blank" attribute, and I want to hide the fact that the words were links in the first place:

var links = document.links;
for (var i = 0, length = links.length; i < length; i++) {
    links[i].onclick = function(e) {
        e = e || window.event;
        e.preventDefault();
    }
}

So I don't want to simply preventDefault() on link click but remove the links completely while keeping the link text, and I want to apply this to target="_blank" links only.

like image 912
Jussi H Avatar asked Jan 28 '26 19:01

Jussi H


2 Answers

$('a[target="_blank"]').each(function(){
   $(this).removeAttr('href');
});

Or if you want to completely remove a tags

$('a[target="_blank"]').each(function(){
   $(this).replaceWith($(this).text());
});

http://jsfiddle.net/mohammadAdil/kZqFD/

like image 71
Mohammad Adil Avatar answered Jan 30 '26 10:01

Mohammad Adil


You can remove the links and replace them with text only doing this:

$('a[target="_blank"]').each(function(){
    var linkText = $(this).text();
    $(this).after(linkText);
    $(this).remove();
});

Demo: http://jsfiddle.net/hXFse/

like image 33
Piet van Dongen Avatar answered Jan 30 '26 11:01

Piet van Dongen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!