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

IT技术 javascript jquery attributes
2021-02-04 14:18:50

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

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

谁能告诉我这是否可行,如果可以,正确的语法是什么?

6个回答

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" }
只是有点想知道为什么我们将它作为数组访问 this[0].attributes
2021-03-17 14:18:50
这是 jQuery.attr()方法的一个非常好的和预期的功能很奇怪 jQuery 没有包含它。
2021-03-19 14:18:50
当没有匹配的元素时,您可能想要修复它,例如 $().attr()
2021-03-20 14:18:50
attributes虽然不是数组……但在 Chrome 中至少它是一个NamedNodeMap,它是一个对象。
2021-03-25 14:18:50
attributes集合包含旧版 IE 中所有可能的属性,而不仅仅是那些在 HTML 中指定的属性。您可以通过使用每个属性specified属性过滤属性列表来解决此问题
2021-04-10 14:18:50

这是可以完成的许多方法的概述,供我自己和您参考:) 这些函数返回属性名称及其值的散列。

香草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 的 Vanilla JS

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

洛达什

比 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="")。

一个调试脚本(基于 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

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