How to get all the attributes of the tag a as an array?

 <a data-key1="5" data-key2="7"></a> 
  • 2
    Attributes can only be data-* ? or others are needed too? - Grundy

1 answer 1

The method .data() is responsible for getting data-* attributes.

To get all the data-* attributes:

 /* Получаем все свойства */ var data = $('#test').data(); /* Для демонстрации */ $('body').append($('<ul>').attr('id', 'result')); /* Выводим свойства */ for (var key in data) { $('<li>', { text: key + ': ' + data[key] }).appendTo('#result'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <a id="test" data-key1="5" data-key2="7"></a> 

To get all the properties:

 /* Получаем все свойства */ var attributes = document.getElementById('test').attributes; /* Для демонстрации */ $('body').append($('<ul>').attr('id', 'result')); /* Перебираем свойства */ for (var key in attributes) { /* Выбираем именно html-атрибуты */ if (attributes[key].nodeName) { $('<li>', { text: attributes[key].nodeName + ': ' + attributes[key].nodeValue }).appendTo('#result'); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <a id="test" data-key1="5" data-key2="7"></a> 

Based on the answers:

  • Note that id not output. - Grundy
  • judging by the example, I suggested that the author needs to display data-* attributes - VenZell
  • he just says everything , I therefore explained to him in the commentary - Grundy
  • Yes thank you! Great solution for custom attributes. Tried to get through .attr() , but did not work. - user199345
  • @Mike, because attr - gives a specific attribute. You can also see the attributes property of the element - all attributes are stored in it. - Grundy