Search code examples
jqueryhyperlinkpreventdefault

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.


Solution

  • $('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/