使用JavaScript获取定位标记URL

时间:2018-08-28 23:03:21

标签: javascript

我正在尝试将锚标记的网址存储在变量中,但是我一直遇到错误。

var buttonUrl = document.getElementById('test').href;

Uncaught TypeError: Cannot read property 'href' of null

2 个答案:

答案 0 :(得分:0)

确保在窗口加载后 后您的代码正在运行:

window.onload = function() {
    var buttonUrl = document.getElementById("test").href;
    console.log(buttonUrl);
    //This will log the href of the "test" element to the console as a debugger. You can now use buttonUrl as you want.
}

答案 1 :(得分:-1)

有时您需要引用元素的索引,例如零。试试这个

var buttonUrl = document.getElementById('test')[0].href