SO Answer / Get all attributes from a HTML tag with JS/jQuery

Link to question in result

by KooiInc MeHere

HTML

<script src="https://rawgit.com/KooiInc/Helpers/master/Helpers.js"></script>
<div class="solink" data-linkid="25832866"></div>

<span name="test1" data-message="test1">test1</span>
<span name="test2" data-message="test2" class="xzy">test2</span>
<span name="test3" data-message="test3">test3</span>
<span name="test4" data-message="test4" style="color:red; background: yellow">test4</span>
<div id="newdiv" data-isnew="true" data-message="It's a div">Some div</div>
<div data-message="It's another div">Another div</div>

<div id="mdnlink" data-link="https://developer.mozilla.org/en-US/docs/Web/API/Element.attributes"
     data-message="a link to MDN">See also...</div>

JavaScript

// retrieve all elements with attribute [data-message]
var elems = document.querySelectorAll('[data-message]'), attrs = [];

for (var i=0; i<elems.length; i+=1) {
    // get or assign id for easy retrieval later on
    if (!elems[i].id) {
        elems[i].id = '_' + (Math.floor(10000+Math.random()*1000000).toString(16));
    }
    // create object for the current element
    var attrobj = {nodeName: elems[i].nodeName, id: elems[i].id, nodeIndex: i};
    [].slice 
      .call(elems[i].attributes) // convert real array from arraylike object
      .map(function(v){ 
             this[v.name] = v.value; return v; 
           }, attrobj);         // use mapping /w initial value attrobj to fill attrobj
    attrs.push(attrobj);        // push to attrs
}

Helpers.log2Screen('<h3>The attributes (<code>attrs</code>) of all elements containing a <code>[data-message]</code> attribute:</h3>');
Helpers.log2Screen(Object.print(attrs));