Search code examples
javascriptclassname

object.className or object.getAttribute("className/class")?


Between both those :

Javascript

function setCss(object, css) {
    return (object.className = css);
}
function getCss(object, css) {
    return object.className;
}

Or

function getCss2(object)
{   
    if (object.getAttribute("className")) {
        return object.getAttribute("className");
    }
    return object.getAttribute("class");
}


function setCss2(object, cssclass)
{        
    if (object.getAttribute("className")) {
        return object.setAttribute("className",cssclass);
    }
    object.setAttribute("class",cssclass);
}

HTML

<a href="#" onClick="setCss(this, 'newclass')" />
<a href="#" class="something" onClick="alert(getCss(this))" />
<a href="#" onClick="setCss2(this, 'newclass')" />
<a href="#" class="something" onClick="alert(getCss2(this))" />

Both version seems to work in IE8, FF4, Chrome, Opera and Safari. (jsFiddle (improved) demo)

Which one is best-usage practice and why? Did you ever run into any issue with either version?


Solution

  • getAttribute("class") is more universal, because it can be used in different types of documents. In XML documents, most importantly. Including SVG.

    element.className works only in HTML. It is described in the DOM level 2 HTML specs.