views:

456

answers:

3

Given an XML element in jQuery like so:

$('<foo oy="vey" foo="bar" here="is" another="attribute" />')

Can I use either jQuery or plain old JavaScript to get an array containing the names of all the attributes in an XML element? I would expect this:

['oy','foo','here','another']
+1  A: 

This plugin will help you do that.

You can also do it using plain old javascript using something like that :

 var elt = document.getElementsByTagName('id'); 
 for (i=0;i<elt.attributes.length;i++){ 
     //elt.attributes[i].nodeName is what you want, .nodeValue for it's value.
 }
Soufiane Hassou
A: 

it will be more easy if you use child elements instead of attributes. :) Then you can parse and get those values real simple.

tony_le_montana
-1. Using child elements can end up being unnecessarily verbose and total overkill, like when you're storing primitive data types (numbers, strings, booleans...).
Matt Ball
my answer was inspired by "XML Elements vs. Attributes" from here http://www.w3schools.com/xml/xml_attributes.asp
tony_le_montana
+2  A: 

The jQuery function isn't really meant to parse XML, it can parse HTML, but it's not really the same.

What about using the browser's XML parser:

function parseXML(text) {
  var parser, xmlDoc;

  if (window.DOMParser) {
    parser = new DOMParser();
    xmlDoc = parser.parseFromString(text,"text/xml");
  } else {  // IE
    xmlDoc=  new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = "false";
    xmlDoc.loadXML(text); 
  }
  return xmlDoc;
}

// Demo
var doc = parseXML('<foo oy="vey" foo="bar" here="is" another="attribute" />');
var foo = doc.childNodes[0];
for (var i = 0; i < foo.attributes.length; i++) {
  var attr = foo.attributes[i];
  alert(attr.name + " = " + attr.value); 
}

Run the above code here.

CMS