Dail
Dail

Reputation: 4606

How to read href attribute with JQuery

I use $(this).attr('href') in JQuery to read the string in href="" attribute. I have those kind of links:

<a href="1"></a>
<a href="2"></a>
<a href="3"></a>

Firefox and Chrome return me the code correctly. IE return me: http://127.0.0.1/1

How can i do?

Upvotes: 0

Views: 2900

Answers (3)

Jonathon Bolster
Jonathon Bolster

Reputation: 15961

You don't need to use the attr function when you're accessing a native property. You could use the anchor element's properties directly to get the pathname (i.e. the HREF without the domain or query string)

Basically: this.pathname

There's a bit of an inconsistency between browsers (some will show a leading forward slash in pathname and others won't). To get around this, just get rid of any potential leading slashes:

this.pathname.replace(/^\//,'')

A working example: http://jsfiddle.net/jonathon/3ET6p/

Even if you choose the other answers, I recommend you use the native .href on the object.


Just as an extra note to this. I fired up a VM of IE6 and all is well :)

Upvotes: 3

Itamar Marom
Itamar Marom

Reputation: 525

I'd suggest checking which browser is being used. If it's IE, check if the current domain is "127.0.0.1". If it's not, do what @Saul suggested.

Upvotes: 0

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19049

Try via DOM element: $(this)[0].href; or $(this)[0].getAttribute("href");

If the result is still the same, I suggest you using something not starting with the number.

.

Upvotes: 1

Related Questions