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?
The
attributes
property contains them all:What you can also do is extending
.attr
so that you can call it like.attr()
to get a plain object of all attributes:Usage:
Using javascript function it is easier to get all the attributes of an element in NamedArrayFormat.
A debugging script (jquery solution based on the answer above by hashchange)
Simple solution by Underscore.js
For example: Get all links text who's parents have class
someClass
Working fiddle
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:
Vanilla JS with Array.reduce
Works for browsers supporting ES 5.1 (2011). Requires IE9+, does not work in IE8.
jQuery
This function expects a jQuery object, not a DOM element.
Underscore
Also works for lodash.
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.
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=""
).with LoDash you could simply do this: