开发者

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?


object.getAttribute("className"); actually does not work.

The difference is that getAttribute gets the value of a HTML attribute as it is written in the HTML code (with some exceptions).

These values are mostly also the initial values of the properties of the DOM element. But accessing them can yield different values, due to pre-/postprocessing.

For example, if you have an <a> element, el.href gives you the complete (absolute) URL, while el.getAttribute('href') gives you the URL as it was written in the HTML.

Most of the time, you want to access the properties of the DOM element, as these reflect the current state of the element.


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.


Use the first one.

It's sorter. It works in every browser even the very old ones that don't support getAttribute. It probably faster too.

But please don't use a function for this. Just use this.className and this.className='newClass'. Using a function is overkill for this.


According to MDN Webdocs its better to use setAttribute/getAttribute, because element.className is not always the string of classes. In case that your element is a SVG path, element.className will suddenly be an instance of a SVGAnimatedString:

className can also be an instance of SVGAnimatedString if the element is an SVGElement. It is better to get/set the className of an element using Element.getAttribute and Element.setAttribute if you are dealing with SVG elements. However, take into account that Element.getAttribute returns null instead of "" if the element has an empty class attribute.

Source: https://developer.mozilla.org/en-US/docs/Web/API/Element/className#notes

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜