使用JavaScript获取元素属性

What I love so much about JavaScript is that the language is incredibly dynamic.  So dynamic that you can modify native objects if you so choose.  One dynamic property I've frequently been using lately is the attributes property of DOM elements.  This attributes property provides me the names and values of every attribute on a given element!

我非常喜欢JavaScript的是,该语言是动态的。 如此动态,您可以选择修改本地对象。 我最近经常使用的一个动态属性是DOM元素的attributes属性。 这个attributes属性为我提供了给定元素上每个属性的名称和值!

HTML (The HTML)

Let's assume we're working with the following element:

假设我们正在使用以下元素:


<div class="myClass" id="myId" title="Some text title">Some text</div>


A simple DIV with a few frequently used attributes.  We can use getAttribute() to get attributes when we know they're there, but how do we simply get an object containing all attributes?

具有一些常用属性的简单DIV。 当我们知道属性存在时,可以使用getAttribute()获取属性,但是如何简单地获取包含所有属性的对象呢?

JavaScript (The JavaScript)

DOM elements have an attributes property which contains all attribute names and values:

DOM元素具有一个attributes属性,其中包含所有属性名称和值:


var attrs = document.getElementById("myId").attributes;

// returns NamedNodeMap {0: class, 1: id, 2: title, ...}


Using Array.prototype.slice.call, which is also helpful in converting NodeLists to Arrays, you can convert the result to a true array which you can iterate over:

使用Array.prototype.slice.call ,这也有助于将NodeLists转换为Arrays ,您可以将结果转换为可以迭代的真实数组:


Array.prototype.slice.call(document.getElementById("myId").attributes).forEach(function(item) {
	console.log(item.name + ': '+ item.value);
});

// class: myClass
// id: myId
// title: Some text title


The attributes property of an element is incredibly handy when you're looking to see what attributes are present without explicitly knowing which to look for; the attributes property provides an awesome level of dynamism.

当您在不显式知道要查找的属性的情况下查看存在的属性时,该元素的attributes属性非常方便。 attributes属性提供了惊人的动态性。

Until I found the need to grab every attribute from an element, I wasn't aware that such a list existed.  Now that I'm aware of the this property, however, I'm trying to think up ways to abuse the information provided to empower elements even more.  If you've ever found a useful use of the attributes property, please share it!

在发现需要从元素中获取每个属性的需求之前,我还不知道存在这样的列表。 现在,我已经知道了此属性,因此我正在尝试寻找一种方法来滥用提供的信息来进一步增强元素的功能。 如果您发现attributes属性的有用用法,请共享它!

翻译自: https://davidwalsh.name/javascript-attributes

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值