Clear Links to Current Page with Unobtrusive JavaScript Version Two

To recap, I wanted some unobtrusive JavaScript that would automatically strip any link that was pointing to the current page. The problem with the first version was that initially, I didn't take anchors into account. A link to a page with an anchor was considered a different URL than one with an anchor. Then next step was to strip the links of all URLs that pointed to the current page regardless of the anchor. This time I went too far since we'd still want skip and top of page links to be active.

In really thinking through the anchors issue, I've come to the following conclusions:

  • If there's a link on the current page with an anchor on it, we don't want to remove the link. Examples: skip and top of page links.
  • BUT, if there's a link to the current page without an anchor then we do want to remove the link.

Therefore, I introduce CLCP: Version Two (.js).

function clearCurrentLink(){
    var a = document.getElementsByTagName("A");
    for(var i=0;i<a.length;i++)
        if(a[i].href == window.location.href.split("#")[0])
            removeNode(a[i]);
}

function removeNode(n){
    if(n.hasChildNodes())
        for(var i=0;i<n.childNodes.length;i++)
            n.parentNode.insertBefore(n.childNodes[i].cloneNode(true),n);
    n.parentNode.removeChild(n);
}

You can also give it a test run.

The only thing that changed from the previous version was the check to see if the link that I'm intending to strip had an anchor on it.

Feel free to leave any suggestions or browser compatibility issues. And thanks to Gabriel Mihalache for the suggestions.

UPDATE: Thankfully, I've got some smart people who read this site. Mark Wubben correctly made the observation that I do not need to split the href of the link that I'm checking. I've updated the code above. Here's the old code:

a[i].href.split("#")[0] ==
 window.location.href.split("#")[0] 
 && a[i].href.indexOf("#") == -1

...which was changed to...

a[i].href == window.location.href.split("#")[0]

As you can see, the logic is much more succinct.

Published November 18, 2004 · Updated September 17, 2005
Categorized as JavaScript
Short URL: http://snook.ca/s/291

Conversation

26 Comments · RSS feed
Mark Wubben said on November 19, 2004

I think the logic is a bit off there. Why split the anchor part of the href if it isn't allowed to have an anchor part at all?

Dave Cardwell said on November 19, 2004

Re: Mark Wubben (Nov 19)

So that if there is an anchor, you can make sure that it is not on a different page.

Dave Cardwell said on November 19, 2004

Sorry, completely the wrong answer there. I'll try again...

The page is /test.html, and on the page is a link to /test.html, and a link to /test.html#top.

If you do not split the anchor part of .href and just check to see if the link and window's .hrefs are equal, going to http://www.mysite.com/test.html#top

a) won't remove the link to /test.html
b) will remove the link to /test.html#top which is usually not desirable

How about values encoded in the URL (ie. /test.html?myvar=1)? As long as it wasn't navigation related (eg. /test.html?page=1), or needed to remain in the URL between pages for some reason, you might want to check for those too.

Now we're getting into regular expression country.

Jonathan Snook said on November 19, 2004

Dave: to address the parameter issue you mention, the code currently sees /test.html?myvar=1 and /test.html?myvar=2 as two seperate URL's. The code could be revised to take this into account but chances are, url parameters indicate a completely different "page" and as a result, it seems best left as is. IE: ?myvar=1 and ?myvar=2 generate two unique pages and therefore a link to one should not disable a link to the other.

Austin Matzko said on November 20, 2004

Jonathan,
Thanks for the handy code.
I noticed that when you request a page by domain name, window.location.href returns "http://www.mysite.com/" instead of "http://www.mysite.com/index.html", so my links to "index.html" are ignored by the script.
So I modified your clearCurrentLink function to add the full index page address (whatever it is) to any window.location.href ending in "/". Hope that helps someone.
Lines changed in clearCurrentLink:
...
var indexpage = "index.html"
var url = window.location.href;
if(url.substr(url.length-1,1)=="/")
url = url + indexpage;
for(var i=0;i

Julian Rodriguez said on February 02, 2005

I'm trying to use the code on this page for my site, but it doesn't work because my links point to index.htm files, and are not recognized.
I'm interested in the code the last guy sent, but it's trimmed, so...

Joseph Huang said on February 19, 2005

Wouldn't this be more appropriate to be done on the server side?

Jonathan Snook said on February 20, 2005

Absolutely, for that I shall refer you to Faux Active Link over at Maratz.com. He's got some PHP code that does just that talks of such. The code I present is simply another option.

Rasmus Johansson said on August 24, 2005

A nice little script you've put together! I tested it on a page with a lot of links. The result got me wondering why it only removed half of the links and what I found out is that the loop criteria a.length actually gets updated for each step.

If you then have a page with 20 links that you want to remove the script starts stepping through the loop, but when i hits the value 10 it will actually stop because 10 links has already been removed from the page and a.length will therefore be 10.

A modified version of the loop that removes all links could look like this:

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

while (a.length > 0)
{
removeNode(a[0]);
a = document.getElementsByTagName("a");
}

Brian said on January 23, 2006

How about a script that DOES remove anchor links, but not the other links?

Michelle said on July 09, 2006

Thanks to a post on one of my favorite forums I was refered here, I have a question I want to use the script but not sure where I should be placing the code. Before the head tag or at the bottom. thank you

Michelle

fredericvigouroux said on September 09, 2006

I spend one day on it, but it's a success.
Thanks a lot for your helpfull script.
Not sure it will be used at the end, but i apreciate a lot.
Best regards
Frederic

roman villarreal said on September 16, 2006

Awesome. Been wanting to do this for awhile. I got it running in seconds.
Thanks a bunch. Nice blog.

kylierose said on October 31, 2006

Does this script work with relative URLs in IE6? I can't seem to get it to work with my local machine in IE (should I be surprised??).

Jonathan Snook said on November 01, 2006

kylierose: yeah, it's unlikely that it'll work locally since I believe the href returned from the browser ends up being something like: c|//documents and settings/... and not just the filename as you'd likely have in the HTML.

kylierose said on November 09, 2006

hmmm - yes that's what i found too. unless you specify absolute paths (which is pointless if you are coding in HTML and using DW Library items - or any other repeated nav elements). Firefox and Opera work like a dream though! Thanks so much for sharing this solution with the world!

automatyk said on December 13, 2006

So close but no cigar!?

Just what I was looking for... but it only removes half of the links! I'm using the script to remove links that are empty or refer to the current page. Unfortunately, I'm confounded as to why it's leaving every other empty href? Any clues?

Jonathan Snook said on December 14, 2006

automatyk: It's hard to say for sure what might be happening. Did you simply drop the code in as-is or make any additional changes? It's possible that removing the node is affecting the length of the nodelist. Which means, you'd have to decrement i each time you remove a node.

automatyk said on December 14, 2006

Jonathan, I'm using your code exactly as is. I'm linking to the clearlink.js from the page and using it to remove the empty links from a series of pictures. For example:

<img src="myimg.jpg">

Thank you.

automatyk said on December 14, 2006

sorry... the example above should be:
<p><a href="" onclick="popup(this.href)"><img src="someimage.jpg"></a></p>

automatyk said on December 15, 2006

I got it to work(almost). I created another array that collects the empty HREFs. Another FOR loop cycles through that array calling the removeNode function.

Works well in Firefox but chokes under IE for some reason.

Tim said on June 13, 2007

Hi Jon, I'de like to have something like this in place of my forums content links.
I'm trying to hide all outbound links on the page. The reason being is we don't want anonymous users to access our links.

Nick said on June 27, 2007

Very nifty, thanks. I modified it slightly to strip the link content (images or text, etc) for specific URLs (not just the current page).

Mike Houghton said on July 23, 2007

Just wanted to say thanks. I regularly work with legacy-generated web templates, and plan to use this technique (combined with Rasmus Johansson's tweak above) to remove all of the <font> tags generated on the sites I'm tweaking.

Dicauhitech said on August 19, 2007

http://tinraovat.myvnc.com/raovat/index.php?mod=vip

Above site seem has Source Code ! Any who help me show it on where segment on it's html. I want use it for my blog

RoobiogyViock said on March 29, 2011

hello world

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.