3

If you run this script http://jsfiddle.net/y8jp8/2/ on IE7 and firefox you can see: Results are not the same.

I just want to see just 3 attribute (id, title and myattr) and it's values. How can I do this in IE?

JohnFx
  • 34,542
  • 18
  • 104
  • 162
Nuri Akman
  • 792
  • 3
  • 18
  • 41

2 Answers2

3

This is a correction to roXon's answer, but still no perfect solution..

var result = "";
var attrs = $("#sample")[0].attributes;

for(var i=0;i<attrs.length;i++) {
    if(attrs[i].nodeValue != null 
    && attrs[i].nodeValue != '' 
    && attrs[i].nodeValue != 'inherit'){
        result += ( attrs[i].nodeName + "=" + attrs[i].nodeValue + "<br>");
    }

    $('#log').html(result);
}

http://jsfiddle.net/digitaloutback/pMVJw/9/

UPDATE:

IE7 doesn't seem to filter out the unspecified attributes, for example, this is the data for the 'sample' attribute in your example:

parentNode => null 
nodeValue => sample 
firstChild => null 
name => id 
expando => false 
lastChild => null 
ownerDocument => [object] 
attributes => null 
previousSibling => null 
value => sample 
nodeType => 2 
nodeName => id 
childNodes => null 
nextSibling => null 
specified => true 
ownerElement => undefined 

Therefore, you need to test against 'specified' like:

var result = "";
var attrs = $("#sample")[0].attributes;

for(var i=0;i<attrs.length;i++) {   

    if(attrs[i].specified === true ) {
        result += ( attrs[i].nodeName + "=" + attrs[i].nodeValue + "<br>");
    }

    $('#log').html(result);

}

http://jsfiddle.net/digitaloutback/pMVJw/10/

digout
  • 4,041
  • 1
  • 31
  • 38
1

Any reason you can't just get the three explicit values you want instead of iterating over all attributes? This gets me the same results in IE7 and Chrome.

http://jsfiddle.net/y8jp8/22/

var result = "";
result += 'id=' + $('#sample').attr('id') + '<br />';
result += 'title=' + $('#sample').attr('title') + '<br />';
result += 'myattr=' + $('#sample').attr('myattr') + '<br />';
$("#log").html( result );
mrtsherman
  • 39,342
  • 23
  • 87
  • 111
  • On my application I stored to many value on elements attribute. Those attribute count may varry. I know, if I change those attribute names with prefix data- (on html5) I can easly get with jQuery data methode – Nuri Akman Nov 27 '11 at 19:19
  • Until change my code to jQuery data methode, I can use this code. But, this is not a perfect solution. – Nuri Akman Nov 27 '11 at 19:20