Monday, October 21, 2013

Get Element Attributes with 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!

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?

The JavaScript

DOM elements have an attributes property which contains all attribute names and values:
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(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.
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!