SOFTELメモ Developer's blog

会社概要 ブログ 調査依頼 採用情報 ...
てるてる動画

【Javascript】a要素のpathnameがIEとIE以外で違う

問題

以下のようなa要素について、

<a href="https://www.softel.co.jp/blogs/tech/">あるリンク</a>

a要素.pathnameプロパティを参照すると、以下のようにブラウザによって取得できる値が違う。

IE以外の場合

/blogs/tech/

IEの場合

blogs/tech/

どっちが正しいの?

答え

あなたの環境ではどちら?

あるリンク ← 問題のリンク

仕様を確認すると、先頭に/(スラッシュ)が付いている方が正しい様子。

pathname

If it has no leading “/” (U+002F) character, prepend a “/” (U+002F) character to the new value

http://www.w3.org/TR/html5/urls.html#urls

Uniform Resource Identifier (URI)

http://tools.ietf.org/html/rfc3986

pathname

This attribute represents the path component of the Location’s URI which consists of everything after the host and port up to and excluding the first question mark (?) or hash mark (#).

http://www.w3.org/TR/Window/#location-attributes

でもIEは違う。

IEでも、window.location.pathname にはスラッシュが付くくせに、a要素ではそうでない。いったい何なんだと、釈然としない気分である。。。

問題が発生する場合は、IEさんには期待しないで、pathname の先頭に /(スラッシュ)がないときは付け足す処理を追加しましょう。

IE対策の例

//取ってきたpathnameの
var x = a.pathname
//先頭がスラッシュならそのまま、スラッシュがない場合は/を付け足す
x = x.indexOf('/') == 0 ? x : '/' + x;

関連するメモ

コメント(1)

IE9以下だとa要素のpathnameが変? | Hokkaidosm bot管理 2015年4月8日 18:39

[…] 【Javascript】a要素のpathnameがIEとIE以外で違う(Softel メモ) […]