1

I'm trying to have every attribute's names and values of an element of the DOM using jQuery and JavaScript. I've written this piece of code:

$.each(attribute.attributes, function (ident, attrib) {
    alert(attrib.value);
    alert(attrib.name);
});

"attribute" is an attribute of the DOM. I've found .attributes method online but I don't know why the program crashes entering in this function.

palaѕн
  • 72,112
  • 17
  • 116
  • 136
Magic AndWebDev
  • 137
  • 1
  • 5
  • 16
  • 3
    Can you show us how the `attribute`-object looks like? – yckart Jun 10 '13 at 17:11
  • Every attribute? I'd probably just do `$("*").each(function() { console.log(this.id); });` -- something about that seems wrong tho. – tymeJV Jun 10 '13 at 17:12
  • 2
    possible dupplicate: http://stackoverflow.com/questions/14645806/get-all-attributes-of-an-element-using-jquery – Jeff Noel Jun 10 '13 at 17:12
  • If you're doing it for the sake of logging, you can try with console.dir(attribute)... FF (Firebug) and Chrome (F12) will be happy to show you object internals! – OzrenTkalcecKrznaric Jun 10 '13 at 17:20

2 Answers2

1
$('.obj').each(function() {
   var attArray = [];
   for(var k = 0; k < this.attributes.length; k++) {
       var attr = this.attributes[k];
       if(attr.name != 'class')
          attArray.push(attr.value);
   }
   alert(attArray[2]); //x = 55
   //do something with attArray here...
});

http://jsfiddle.net/tjuFH/3/

Source

Community
  • 1
  • 1
Johan
  • 35,120
  • 54
  • 178
  • 293
0

Credits

JavaScript

$(this).each(function() {
  $.each(this.attributes, function() {
    // this.attributes is not a plain object, but an array
    // of attribute nodes, which contain both the name and value
    if(this.specified) {
      console.log(this.name, this.value);
    }
  });
});
Community
  • 1
  • 1
Jeff Noel
  • 7,500
  • 4
  • 40
  • 66