タイトル通りで、少しハマったのでメモ。
以下のようなAタグ(hrefが#や空のリンクタグ)があるとする。
<a href="#" id="link1">#リンク</a> <a href=""id="link2">空リンク</a>
DOM Elementのhrefメソッドを使って取得すると、以下のようになる。
document.getElementById("link1").href
// 「$現在のページのURL+#」 が返ってくる
// 例) http://example.com#
document.getElementById("link2").href
// 「$現在のページのURL」 が返ってくる
// 例) http://example.com
HTMLの通り、#や空の文字列が欲しい場合、getAttribute() を使う必要がある。
document.getElementById("link1").getAttribute("href")
// 「#」 が取得できる
document.getElementById("link2").getAttribute("href")
// 「 」 が取得できる
「.href」と「.getAttribute(“href”)」、同じだと思っていた。