HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Get all the attributes of a DOM Node

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theallnodeattributesgetdom

Problem

I needed this small function for one of my project.

Fetch Attributes

function fetchAttrs(node) {

  if (!node || !node.hasAttributes()) return {};
  var attrs = node.attributes;
  var res = {};
  var length = attrs.length;
  for (var i = 0; i < length; i++) {
    var attr = attrs[i];
    res[attr.name] = attr.value;
  }
  return res;
}


It's working fine as expected but I wanted to know if I am missing something from a performance point of view or good coding practices. Just need a second opinion :)

Update

How to handle exceptions, is it a good practice?

Solution

There's not much of a performance difference between the two (reduce is very slightly favoured in my own tests), but I prefer the more readable reduce function over the for loop. I believe it makes the code simpler, too. Also sort of a personal preference - why not use the full name? No real need in shortening it. :-)

var fetchAttributes = function(node) {
  return node && Array.prototype.reduce.call(node.attributes, function(list, attribute) {
    list[attribute.name] = attribute.value;
    return list;
  }, {}) || {};
};


http://jsperf.com/reduce-vs-for-fetch-attributes

Edit: In fact you can simplify this further, as you aren't transforming the attributes in any way.

var fetchAttributes = function(node) {
    return node && node.attributes || {};
};

Code Snippets

var fetchAttributes = function(node) {
  return node && Array.prototype.reduce.call(node.attributes, function(list, attribute) {
    list[attribute.name] = attribute.value;
    return list;
  }, {}) || {};
};
var fetchAttributes = function(node) {
    return node && node.attributes || {};
};

Context

StackExchange Code Review Q#67281, answer score: 4

Revisions (0)

No revisions yet.