[javascript] Get all attributes of an element using jQuery

I am trying to go through an element and get all the attributes of that element to output them, for example an tag may have 3 or more attributes, unknown to me and I need to get the names and values of these attributes. I was thinking something along the lines of:

$(this).attr().each(function(index, element) {
    var name = $(this).name;
    var value = $(this).value;
    //Do something with name and value...
});

Could anyone tell me if this is even possible, and if so what the correct syntax would be?

This question is related to javascript jquery attributes

The answer is


Simple solution by Underscore.js

For example: Get all links text who's parents have class someClass

_.pluck($('.someClass').find('a'), 'text');

Working fiddle


Here is a one-liner for you.

JQuery Users:

Replace $jQueryObject with your jQuery object. i.e $('div').

Object.values($jQueryObject.get(0).attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));

Vanilla Javascript Users:

Replace $domElement with your HTML DOM selector. i.e document.getElementById('demo').

Object.values($domElement.attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));

Cheers!!


Using javascript function it is easier to get all the attributes of an element in NamedArrayFormat.

_x000D_
_x000D_
$("#myTestDiv").click(function(){_x000D_
  var attrs = document.getElementById("myTestDiv").attributes;_x000D_
  $.each(attrs,function(i,elem){_x000D_
    $("#attrs").html(    $("#attrs").html()+"<br><b>"+elem.name+"</b>:<i>"+elem.value+"</i>");_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>_x000D_
<div id="myTestDiv" ekind="div" etype="text" name="stack">_x000D_
click This_x000D_
</div>_x000D_
<div id="attrs">Attributes are <div>
_x000D_
_x000D_
_x000D_


A debugging script (jquery solution based on the answer above by hashchange)

function getAttributes ( $node ) {
      $.each( $node[0].attributes, function ( index, attribute ) {
      console.log(attribute.name+':'+attribute.value);
   } );
}

getAttributes($(this));  // find out what attributes are available

Here is an overview of the many ways that can be done, for my own reference as well as yours :) The functions return a hash of attribute names and their values.

Vanilla JS:

function getAttributes ( node ) {
    var i,
        attributeNodes = node.attributes,
        length = attributeNodes.length,
        attrs = {};

    for ( i = 0; i < length; i++ ) attrs[attributeNodes[i].name] = attributeNodes[i].value;
    return attrs;
}

Vanilla JS with Array.reduce

Works for browsers supporting ES 5.1 (2011). Requires IE9+, does not work in IE8.

function getAttributes ( node ) {
    var attributeNodeArray = Array.prototype.slice.call( node.attributes );

    return attributeNodeArray.reduce( function ( attrs, attribute ) {
        attrs[attribute.name] = attribute.value;
        return attrs;
    }, {} );
}

jQuery

This function expects a jQuery object, not a DOM element.

function getAttributes ( $node ) {
    var attrs = {};
    $.each( $node[0].attributes, function ( index, attribute ) {
        attrs[attribute.name] = attribute.value;
    } );

    return attrs;
}

Underscore

Also works for lodash.

function getAttributes ( node ) {
    return _.reduce( node.attributes, function ( attrs, attribute ) {
        attrs[attribute.name] = attribute.value;
        return attrs;
    }, {} );
}

lodash

Is even more concise than the Underscore version, but only works for lodash, not for Underscore. Requires IE9+, is buggy in IE8. Kudos to @AlJey for that one.

function getAttributes ( node ) {
    return _.transform( node.attributes, function ( attrs, attribute ) {
        attrs[attribute.name] = attribute.value;
    }, {} );
}

Test page

At JS Bin, there is a live test page covering all these functions. The test includes boolean attributes (hidden) and enumerated attributes (contenteditable="").


My suggestion:

$.fn.attrs = function (fnc) {
    var obj = {};
    $.each(this[0].attributes, function() {
        if(this.name == 'value') return; // Avoid someone (optional)
        if(this.specified) obj[this.name] = this.value;
    });
    return obj;
}

var a = $(el).attrs();


with LoDash you could simply do this:

_.transform(this.attributes, function (result, item) {
  item.specified && (result[item.name] = item.value);
}, {});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to attributes

Get the name of a pandas DataFrame What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag? AttributeError: can't set attribute in python How can I disable selected attribute from select2() dropdown Jquery? How do I pass multiple attributes into an Angular.js attribute directive? AngularJS - Attribute directive input value change Are complex expressions possible in ng-hide / ng-show? Get all attributes of an element using jQuery Removing html5 required attribute with jQuery Set attribute without value