-1

I want to put all attributes in a Html element into an array: like i have a jQuery Object, whichs html looks like this:

< span name="test" message="test2"> < /span>

now one way is to use the xml parser described here, but then i need to know how to get the html code of my object.

the other way is to make it with jquery, but how? the amount of attributes and the names are generic.

Thanks

Btw: I can't access the element with document.getelementbyid or something similar.

iCrazybest
  • 2,935
  • 2
  • 24
  • 24
  • Could you show the rest of your HTML? There may well be some way to select the element... – kmoe Sep 14 '14 at 11:49
  • *"xml parser described here"* - where..? O.o – T J Sep 14 '14 at 12:19
  • Guess he means the copied question .. http://stackoverflow.com/questions/2048720/get-all-attributes-from-a-html-element-with-javascript-jquery – Pr0gr4mm3r Sep 14 '14 at 12:34
  • Btw.. if you read your copied question completely instead of just copying it, you would have seen, that one provided answer does exactly what you want ... http://stackoverflow.com/questions/2048720/get-all-attributes-from-a-html-element-with-javascript-jquery#5282801 – Pr0gr4mm3r Sep 14 '14 at 12:36

1 Answers1

0

You can use [element].attributes to retrieve an array of attribute objects from a html element. If you want to map the attributes to an Array of objects with name-value pairs, something like this may be an idea:

Say you have a few spans:

<span name="test1" data-message="test1">test1</span>
<span name="test2" data-message="test2" class="xzy">test2</span>
<span ...>...</span>

You can create an array of name-value pairs like this:

var elems = document.querySelectorAll('[data-message]')
   ,attrs = [];

for (var i=0; i < elems.length; i+=1) {
    var attrobj = {nodeName: elems[i].nodeName, nodeIndex: i};
    [].slice
      .call(elems[i].attributes)
      .map(function(v){ this[v.name] = v.value; return v; }, attrobj);
    attrs.push(attrobj);
}
// first element of attrs (attrs[0]):
// {nodeName: 'SPAN', nodeIndex: 0, name: 'test1', data-message: 'test1' }

Here's a jsFiddle

See also ...

KooiInc
  • 119,216
  • 31
  • 141
  • 177