views:

583

answers:

2

Can it really be true that the attr("href") command for a link is handled very different in IE7 in comparison to all other browsers?

Let's say I have a page at http://example.com/page.html and I have this HTML:

<a href="#someAnchor" class="lnkTest">Link text</a>

and this jQuery:

var strHref = $(".lnkTest").attr("href");

Then in IE7 the value of the strHref variable will be "http://example.com/page.htm#someAnchor" but in other browsers it will be "#someAnchor".

I believe that the last mentioned case is the most correct one, so is it just a case of IE7 being a bad boy or is it a bug in jQuery?

+3  A: 

It's certainly not a bug in jQuery but instead browsers' inconsistent implementations of .getAttribute('href') - I suggest using just .get(0).href for consistency.

Seems like you can access the attribute text in IE and Mozilla using .get(0).getAttribute('href', 2) if you don't want the absolute URI. Note however this won't work in Opera and I haven't tested in Safari/Chrome/anything else.

You could also strip out the domain or split on '#' for .get(0).href and use the second part of the array assuming it even contains '#' ( check .length ).

http://www.glennjones.net/Post/809/getAttributehrefbug.htm

meder
It was not a question about how to retrieve the anchor part of the href. I figured that one out myself. I was just curious about why the difference exists.But thanks a lot for answering anyway. I needed to get the anchor part so I just used substring to extract the correct value :)
EmKay
A: 

I use:

var hrefArr = $(this).attr('href').split('/');
var id = hrefArr[hrefArr.length-1];

when I need everything after the last "/".

Christian
But then what if the href is "http://example.com/folder/page.htm" or simply "/folder/page.htm"?Then you will only get "page.htm" and this is not correct.
EmKay
This was just to show a simple example. I don't have at code example here, but you could run through the array and check for strings. For instance all strings after a substing that contains ".com" at the end. Straight forward....
Christian