使用jQuery获取元素的所有属性

我试图通过一个元素,并获得该元素的所有属性输出它们,例如一个标签可能有3个或更多的属性,我不知道,我需要得到这些属性的名称和值。 我在想:

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

任何人都可以告诉我,如果这是可能的,如果是这样的话是正确的语法?

attributes属性包含它们全部:

 $(this).each(function() { $.each(this.attributes, function() { // this.attributes is not a plain object, but an array // of attribute nodes, which contain both the name and value if(this.specified) { console.log(this.name, this.value); } }); }); 

你也可以做的就是扩展.attr这样你就可以像.attr()那样调用它来获得所有属性的普通对象:

 (function(old) { $.fn.attr = function() { if(arguments.length === 0) { if(this.length === 0) { return null; } var obj = {}; $.each(this[0].attributes, function() { if(this.specified) { obj[this.name] = this.value; } }); return obj; } return old.apply(this, arguments); }; })($.fn.attr); 

用法:

 var $div = $("<div data-a='1' id='b'>"); $div.attr(); // { "data-a": "1", "id": "b" } 

以下是可以完成的许多方法的概述,对于我自己的引用以及你自己:)这些函数返回属性名称及其值的散列。

香草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与Array.reduce

适用于支持ES 5.1(2011)的浏览器。 需要IE9 +,不能在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的

这个函数需要一个jQuery对象,而不是一个DOM元素。

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

下划线

也适用于lodash。

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

lodash

比Underscore版本更简洁,但只适用于lodash,不适用于Underscore。 需要IE9 +,在IE8中是越野车。 荣誉@AlJey 那个 。

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

testing页面

在JS Bin,有一个覆盖所有这些function的实时testing页面 。 testing包括布尔属性( hidden )和枚举属性( contenteditable="" )。

用LoDash你可以简单地做到这一点:

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

使用javascript函数可以更容易地获得NamedArrayFormat中元素的所有属性。

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