getAttribute cannot return class in IE7?

2019-02-12 11:10发布

问题:

I need to find random nodes according to random attribute values. To do that I use getAtrribute on nodes from getElementsByTagName.

It seems like when I look for class name as attribute it does not work on IE (works on FF).

Anyone know if getAtrribute doesn't work only on 'class' or other attributes as well? (if its only class I'll do a workaround.)

回答1:

It's worth testing all of your Javascript cross-platform, if you're not using something like jQuery to take the pain away, but Class may just be a special case.

This should be a cross-platform way of getting the class:

element.className


回答2:

Anyone know if getAtrribute doesn't work only on 'class' or other attributes as well?

It fails for all attributes where the HTML attribute name differs from the DOM property name (className, htmlFor), plus you have to use the DOM-style capitalisation. It also returns the wrong datatype for attributes whose DOM properties aren't strings:

disabled, readOnly, checked, selected, multiple,
compact, declare, isMap, noHref, defer, noResize,
size, cols, rows, width, height, hspace, vspace,
maxLength, tabIndex, colSpan, rowSpan

and possibly others I've missed!

element.getAttribute(x)

in IE is exactly the same as saying:

element[x]

So in general you should avoid using getAttribute, and use the simple DOM Level 1/2 HTML interfaces such as ‘element.className’ instead.

This is finally fixed in IE8.



回答3:

IE is broken in this respect. You can access the class in IE via getAttribute("className") but of course this isn't really the attribute so it doesn't work in !IE.

That leaves you with a choice of branching to get element.className or branching to getAttribute on "className" or "class". Not good.



回答4:

You can grab a list of all attributes from your elements and test their value that way. This snippet handles both IE and WebKit browsers, and will return the string value of the CSS class:

var value = "";
var elements = document.getElementsByTagName("div");

for(var i = 0; i < elements.length; i++){
    if(typeof elements[i].attributes['class'] == "undefined"){
        value = elements[i].getAttribute("class"); 
    } else {
      value = elements[i].attributes['class'].nodeValue;
    }

    alert(value); // careful, this will be a lot of alerts
}


回答5:

Here you can get and set the class attribute with cross browser compatibility.

      //also works with IE7 and below

      //get class attribute value
      var class_name = document.getElementById('elem_id').className;

      //set class attribute
      document.getElementById('elem_id').className  = 'new-class-name';