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

148

我想遍历一个元素,并获取该元素的所有属性以输出它们,例如一个标签可能有3个或更多未知的属性,我需要获取这些属性的名称和值。 我考虑使用以下方法:

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

有人能告诉我这是否可能,如果可能的话,正确的语法是什么?

8个回答

276

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" }

1
当没有匹配的元素时,您可能需要修复它,例如 $().attr() - Alexander
12
attributes 集合包含旧版 IE 中的所有可能属性,而不仅限于在 HTML 中已指定的属性。您可以通过使用每个属性的 specified 属性来过滤属性列表来解决此问题。 - Tim Down
7
这是 jQuery 的 .attr() 方法非常好且预期的功能。奇怪的是,jQuery 没有包含它。 - ivkremer
有点好奇为什么我们要将this[0].attributes作为数组来访问它? - Vishal
1
“attributes” 虽然不是一个数组,在Chrome中它是一个 “NamedNodeMap”,也就是一个对象。 - Samuel Edwin Ward
显示剩余2条评论

31

以下是多种实现方式的概述,供我和您参考 :) 这些函数返回属性名称及其值的哈希表。

原生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;
}

使用Array.reduce进行原生JavaScript编程

适用于支持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;
    }, {} );
}

测试页面

在JS Bin上,有一个实时测试页面,涵盖了所有这些功能。测试包括布尔属性(hidden)和枚举属性(contenteditable="")。


4
一个调试脚本(基于上面hashchange回答的jquery解决方案)
function getAttributes ( $node ) {
      $.each( $node[0].attributes, function ( index, attribute ) {
      console.log(attribute.name+':'+attribute.value);
   } );
}

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

3
使用LoDash,您可以轻松地做到这一点:
_.transform(this.attributes, function (result, item) {
  item.specified && (result[item.name] = item.value);
}, {});

1

这里有一个一行代码供您使用。

JQuery 用户:

$jQueryObject 替换为您的 jQuery 对象。例如:$('div')

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

纯JavaScript用户:

$domElement替换为您的HTML DOM选择器。例如:document.getElementById('demo')

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

干杯!!


0

我的建议:

$.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();


0
使用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>


0

使用Underscore.js的简单解决方案

例如:获取所有链接文本,其父元素具有someClass

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

工作的Fiddle


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接