首页 > 解决方案 > 如何从元素中获取属性?

问题描述

我知道这 4 个属性 getElementById、getElementsByClassName、getElementsByTagName 和 getElementsByName 但 Facebook 有一个有趣的属性,称为 ajaxify

<a role="button" class="_42ft _4jy0 _4jy3 _517h _51sy" href="#" ajaxify="/ajax/groups/mall/approve/?group_id=29702291481682&amp;message_ids=490372844781280" rel="async-post">

是的...,我只想学习如何获取自定义属性

标签: javascripthtmlcssattributeselement

解决方案


querySelector()如果您想根据您将使用或querySelectorAll()使用Attribute Selector的属性获取特定元素。

const el = document.querySelector('[ajaxify]');
console.log(el.getAttribute('ajaxify'));
<div>
  <a role="button" class="_42ft _4jy0 _4jy3 _517h _51sy" href="#" ajaxify="/ajax/groups/mall/approve/?group_id=29702291481682&amp;message_ids=490372844781280" rel="async-post">dasdas</a> - 
  <a href="somewhere.com">somewhere.com</a>
</div>

第一行查找具有名为 的属性的第一个元素'ajaxify'

第二行获取该'ajaxify'元素的属性值。


推荐阅读