Get Element Attributes with JavaScript

By  on  

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!

Recent Features

  • By
    Regular Expressions for the Rest of Us

    Sooner or later you'll run across a regular expression. With their cryptic syntax, confusing documentation and massive learning curve, most developers settle for copying and pasting them from StackOverflow and hoping they work. But what if you could decode regular expressions and harness their power? In...

  • By
    39 Shirts &#8211; Leaving Mozilla

    In 2001 I had just graduated from a small town high school and headed off to a small town college. I found myself in the quaint computer lab where the substandard computers featured two browsers: Internet Explorer and Mozilla. It was this lab where I fell...

Incredible Demos

  • By
    WordPress-Style Comment Controls Using MooTools or jQuery

    WordPress has a nice little effect on the Admin Dashboard where it shows and hides the comment control links when you mouseover and mouseout of the record's container. Here's how to achieve that effect using MooTools or jQuery. The XHTML Notice that we place the links into...

  • By
    Ana Tudor&#8217;s Favorite CodePen Demos

    Cocoon I love canvas, I love interactive demos and I don't think I have ever been more impressed by somebody's work than when I discovered what Tiffany Rayside has created on CodePen. So I had to start off with one of her interactive canvas pens, even though...

Discussion

  1. One useful way to use attributes is for « cloning » (esp. data-*).

  2. MaxArt

    As far as HTML elements are concerned, I used the attributes property just to create a polyfill for the dataset property in browsers supporting Object.defineProperty.

    I used it also in XML documents when I want to make a special conversion of a node into a Javascript object:

    var attrs = elem.attributes, obj = {}, i = 0;
    for (; i < attrs.length; i++) {
        obj[attrs[i].name] = attrs[i].value;
    }
    

    By the way, David: it's item.value, not item.property.

  3. I was right now working on a reflection way of mapping properties and css properties even in-line.

    For those who are using ZeptoJS or JQuery Here is a plugin.

    (function($) {
        $.fn.getAttributes = function() {
            var attributes = {}; 
    
            if( this.length ) {
                $.each( this[0].attributes, function( index, attr ) {
                    attributes[ attr.name ] = attr.value;
                } ); 
            }
            return attributes;
        };
    })();
    
  4. Arthur

    Recently I’m working on a way of grab all attributes to make changes in function of media query. Some behaviors need to be disabled and and that way it’s only done by js

  5. A more efficient way to get all element attributes is to use getAttributeNames() with getAttribute();

    const elementAttributes = (elem) =>
      elem.getAttributeNames().reduce((attrMap, name) => {
        attrMap[name] = elem.getAttribute(name);
        return attrMap;
      }, {});
    

    And a heads up that attributes is not supported in older versions of IE and new versions return a object map instead of index. It also doesn’t support getAttributeNames.

    sources:
    * https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNames
    * https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!