Получить все атрибуты элемента с помощью jQuery - программирование
Подтвердить что ты не робот

Получить все атрибуты элемента с помощью jQuery

Я пытаюсь пройти через элемент и получить все атрибуты этого элемента для их вывода, например, у тега могут быть 3 или более атрибутов, неизвестных мне, и мне нужно получить имена и значения этих атрибутов. Я думал что-то вроде:

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

Может ли кто-нибудь сказать мне, возможно ли это, и если да, то какой будет правильный синтаксис?

4b9b3361

Ответ 1

Свойство 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" }

Ответ 2

Вот краткий обзор многих способов, которые можно сделать, для моей собственной справки, а также для вашей :) Функции возвращают хэш имен атрибутов и их значений.

Ваниль 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;
}

Ваниль 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;
}

Нижнее подчеркивание

Также работает для Лодаш.

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="").

Ответ 3

с помощью LoDash вы можете просто сделать это:

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

Ответ 4

Скрипт отладки (решение jquery на основе ответа выше hashchange)

function getAttributes ( $node ) {
      $.each( $node[0].attributes, function ( index, attribute ) {
      console.log(attribute.name+':'+attribute.value);
   } );
}

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

Ответ 5

Используя функцию 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>

Ответ 6

Простое решение от Underscore.js

Например: Получить текст всех ссылок, у кого есть класс someClass

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

Рабочая скрипка

Ответ 7

Мое предложение:

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