Search code examples
javascriptclassinternet-explorer-7

How can I reliably set the class attr w/JavaScript on IE, FF, Chrome, etc.?


I am using the below JS code in order to change the class when a link is clicked.

document.getElementById("gifts").setAttribute("class", "gkvSprite selected");

This is not working in IE but it does in FF and Chrome. Then I changed the code to:

document.getElementById("gifts").setAttribute("className", "gkvSprite selected");

Then it worked in IE, but stopped working in FF and Chrome.

Could someone please help me out here?


Solution

  • Now that IE is well and truly gone, you can use setAttribute("class", ___) reliably.

    Alternatively, you can reliably use the className property instead of setAttribute:

    document.getElementById("gifts").className = "gkvSprite selected";
    

    More generally, there are a couple of attribute names that IE (and only IE) got wrong with setAttribute: IE required className instead of class, and htmlFor instead of for. The reflected property names are className and htmlFor, but the attribute names are class and for, and setAttribute should be using the attribute names (and does, except on IE). (IIRC, IE11 fixed this, but it doesn't matter now that IE has been retired.)