getAttributes

Получить все атрибуты заданного HTML элемента в форме простого объекта, где ключами являются имена атрибутов, а значениями - сами значения атрибутов. Если элемент не задан, вернуть null.

by Kate Pshidatok

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.4.5/mocha.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.5.0/chai.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.4.5/mocha.min.css">
<div id="mocha">
</div>

<div id="testArea" class="hidden">
  <h1></h1>
  <div id="singleAttribute"></div>
  <div id="multiAttribute" class="some-class" title="Watch this!" width="100%"></div>
</div>

<script>
  mocha.setup('bdd');
  var assert = chai.assert;
  var expect = chai.expect;

</script>
<script>
  describe("markRows", function() {
    before(function() {
      chai.config.includeStack = false;
    });
    describe("формат", function() {
      it("объявлена", function() {
        assert.isFunction(getAttributes);
      });
      it("принимает один аргумент", function() {
        assert.equal(getAttributes.length, 1);
      });
    });

    describe("основные тесты", function() {
      it("элемент не задан", function() {
      	assert.isNull(getAttributes());
      });
      it("без атрибутов", function() {
      	assert.deepEqual(getAttributes(document.querySelector('#testArea>h1')), {});
      });
      it("один атрибут", function() {
      	assert.deepEqual(getAttributes(document.getElementById('singleAttribute')), {
          id: 'singleAttribute'
        });
      });
      it("несколько атрибутов", function() {
      	assert.deepEqual(getAttributes(document.getElementById('multiAttribute')), {
          id: 'multiAttribute',
          'class': 'some-class',
          title: 'Watch this!',
          width: '100%'
        });      
      });
    });

  });
  mocha.run();

</script>

CSS

.hidden{
  display: none;
}

JavaScript

function getAttributes(element) {
 	if (element === undefined){
 		console.log('null')
 		return null;
 	}else{
 		var attrs = element.attributes; 
 		if(attrs.length > 0){
		    for (var i = 0; i < attrs.length; i++) {
		    console.log( attrs[i].name + " = " + attrs[i].value );
		    }
		}else{//не верно
		    console.log('нет атрибутов');
		}
	}
}
getAttributes(multiAttribute);