views:

225

answers:

2

What's The Problem?

Only in Internet Explorer (surprise) is my code executed incorrectly. The short crap of code below should append an "onclick" action to each "a" tag. This works wonderfully but look at the fifth line, it should set the second function argument to the value of the "href" attribute of the anchor tag. In WebKit, Mozilla etc. it's fine. If we set "href" to say "lorem_ipsum" then WebKit, Mozilla etc. retrieve the correct result and set the second function argument to "lorem_ipsum", Internet Explorer prefixes "http://www.some.site/" so we see "http://www.some.site/lorem_ipsum" reported as the second argument. Internet Explorer is incorrect as that is not the "href" attribute of the anchor tag's actual value.

Anchors=Parent.getElementsByTagName("a");
Anchor=0;
while(Anchor<Anchors.length){
    Anchors[Anchor].onclick=function(){
        Plot("",this.getAttribute("href"));
        return false;
    };
    Anchor++;
};

How can I get around this absurd problem? Would I need to strip away from the string everything before the final slash? That seems a long winded approach! Any Ideas?

+1  A: 

Easy...

Anchors[Anchor].onclick=function() {
    var href = this.href || this.getAttribute("href");
    if(href.indexOf(location.href) >= 0)
      href = href.substring(location.href.length);

    Plot("", href);
    return false;
};
Josh Stodola
Thanks for the fast reply. Could you please explain your answer so I can see why it has happened and how you have fixed it. KR, Jay
Jay
location.href is a pre-defined variable containing the URL of the current window. I grab the HREF attribute from the link, and if it contains this value, I substring it to strip it out. Simple.
Josh Stodola
I believe that won't work if the page specifies a BASE tag. I believe the issue where getAttribute(HREF) returns the fully qualified URL was fixed in IE8 standards mode. http://msdn.microsoft.com/en-us/library/ms535173%28VS.85%29.aspx#
EricLaw -MSFT-
I'm not putting code in there to work around a BASE tag because nobody uses them.
Josh Stodola
A: 

A simpler solution is to use the "2" flag that MSFT provided for getting the source value of HREF instead of the absolute value (and which is ignored other browsers):

this.getAttribute("href", 2)

Ref: http://www.quirksmode.org/bugreports/archives/2005/02/getAttributeHREF_is_always_absolute.html

RwL
This only works well in I.E.6. Everything else behaves how it happens to fancy, including I.E.7, sorry.
Jay
Not sure what you mean... I just double-checked IE7 and, like IE6, it returns a full path for getAttribute('href') and the desired source-defined, relative path for getAttribute('href', 2).IE8, Firefox, and Safari return the source value (relative path) for either getAttribute('href') or getAttribute('href', 2).So if you want the source-defined path, as in the original post, you can use ('href', 2) pretty reliably, no?
RwL