views:

1189

answers:

3

Hi

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.

+9  A: 

if you just want the dom attributes, it's probably simpler to use the attributes nodelist on the element itself:

var el = document.getElementById("someId");
var arr = [];
for (var i=0, attrs=el.attributes, l=attrs.length; i<l; i++){
    arr.push(attrs.item(i).nodeName);
}

Note that this fills the array only with attribute names. If you need the attribute value, you can use the nodeValue property:

var nodes=[], values=[];
for (var attr, i=0, attrs=el.attributes, l=attrs.length; i<l; i++){
    attr = attrs.item(i)
    names.push(attr.nodeName);
    values.push(attr.nodeValue);
}
Roland Bouman
The problem is that i can't use getElementById, it's a jquery object.is there a way that i can make getelementbyclassname inside a context like at jquery?
k0ni
You can use `getElementById` - `var el = document.getElementById($(myObj).attr("id"));`
Jonathan Sampson
You can get the DOM object from a jQuery object via the `get` method...e.g.: `var obj = $('#example').get(0);`
Matt Huggins
A: 

In javascript:

var attributes;
var spans = document.getElementsByTagName("span");
for(var s in spans){
  if (spans[s].getAttribute('name') === 'test') {
     attributes = spans[s].attributes;
     break;
  }
}

To access the attributes names and values:

attributes[0].nodeName
attributes[0].nodeValue
Marwan Aouida
A: 

http://plugins.jquery.com/project/getAttributes

Kniganapolke
Thank you, this is a very nice plugin!
k0ni
third party solutions are not how-to answers IMO
stimpy77
stimpy77: shouldn't developers rather reuse than develop from scratch?
Kniganapolke
is there no way to do with pure jQuery?
sunglim