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
属性的有用用法,请共享它!