Get pathname from href in Javascript

whats the simplest way to return the "pathname" from an anchor tags href attribute?

example... say I have:

<a href="http://www.example.com/this/is/my/path.html">Blah</a>

I need to return only this "/this/is/my/path.html" part.

Ideas? I'm using jQuery if it helps..

Thanks!

Answers:

Answer

I think you can use pathname

$('a')[0].pathname;
Answer

see working example here.. http://jsfiddle.net/TvNmL/

HTML..

<a id='lnk' href="http://www.example.com/this/is/my/path.html">Blah</a>

javascript...

alert( document.getElementById('lnk').pathname);
Answer

I noticed there's still no proper answer that deals with the IE bug that @Funka mentioned, so here's my solution:

HTML

<a href="/foo" id="foo">My link</a>

JS

document.getElementById("foo").getAttribute("href");

results '/foo' on all browsers

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.