Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get all HTML attributes

Tags:

html

jquery

is there a way to get the list of attributes set to an element?

example:

<div id="myID" title="I am Title" myAttr="I am something else">Hello World!!!</div>

Is there a way to get all the above attributes?

I tried this already but nothing so far:

$('#myID').attr();

I tried this as well:

$('#myID').attr().each(function(a,b){
    alert(a);
});

did not help either... so any suggestions would be appreciated.

thanks.

like image 578
Val Avatar asked Jan 10 '10 23:01

Val


2 Answers

Use this plugin: http://plugins.jquery.com/project/getAttributes

like image 177
Jan Hančič Avatar answered Oct 02 '22 21:10

Jan Hančič


You can use the DOM attributes property on the underlying jQuery element to extract a NamedNodeMap containing all of the element's attributes. This can be quickly parsed into an object which could be passed directly to .attr().

var attrs = {};
var attrMap = $('#myID')[0].attributes;
$.each(attrMap, function(i,e) { attrs[e.nodeName] = e.nodeValue; });

attrs is now:

{id: "myID", title: "I am Title", myattr: "I am something else"}

Here's a jsfiddle that shows how this works: http://jsfiddle.net/joemaller/cDYtr/

like image 44
joemaller Avatar answered Oct 02 '22 21:10

joemaller