Select 属性 DOM 属性中的一个对象

Select an object property within an attribute of the DOM

我查看了这个帖子,但没有帮助:Find an element in DOM based on an attribute value

我需要一个 Vanilla JS 解决方案来 select DOM 中 <a> 标签的自定义属性中的用户名。我使用 const users = document.querySelectorAll('a[metadata]') 其中 returns 所有 <a> 标签及其所有属性的节点列表。如果我输入 console.log(users[0]),我会得到:

<a href="#" class="btn-normal" metadata="
{
'username':'johnny134',
'category':'shoes',
'summary':'Just a guy called Johnny',
'userId':1223432432
}"
</a>

要访问用户名,我已经尝试 const usernames = document.querySelectorAll('a[metadata="username"]'); 但只是返回未定义。我认为我的问题是用户名在一个对象中,我不知道如何 select 它。

提前致谢

首先,请注意 document.querySelectorAll returns 匹配给定查询的 元素 的列表,而不是这些元素的属性值的列表您在查询中指定的。

const users = document.querySelectorAll('a[metadata]'),您可以获得第一个元素的 metadata 属性,例如:

const metadata0 = users[0].getAttribute("metadata");

然后,因为它是一个 JSON 字符串,所以您解析它:

const user0 = JSON.parse(metadata0);

现在您可以像使用常规 JavaScript 对象一样使用 user0

user0.username
// johnny134

P.S。元数据属性中的 JSON 无效,您尝试解析它时可能会出错。在 JSON 中使用双引号,而不是单引号。