首页 > 解决方案 > 如何使用 Javascript 访问严格/显式 href 值?

问题描述

给定以下锚点:

<a class="example" href="record1234">link</a>

如何href使用 vanilla Javascript 检索实际值?

const link = document.querySelector('.example');

console.log(link.href);
// https://exampledomain.com/current/document/path/record1234

console.log(link.pathname)
// /current/document/path/record1234

// with jQuery
$('.example').attr('href');

// what I want to do:
console.log(link.href.string); // record1234

标签: javascript

解决方案


.getAttribute在元素上 使用。

const link = document.querySelector('.example');
console.log(link.getAttribute('href'));
<a class="example" href="record1234">link</a>


推荐阅读