object.className or object.getAttribute(“className/class”)?

前端 未结 3 646
后悔当初
后悔当初 2021-01-12 13:00

Between both those :

Javascript

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


        
相关标签:
3条回答
  • 2021-01-12 13:40

    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.

    0 讨论(0)
  • 2021-01-12 13:54

    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.

    0 讨论(0)
  • 2021-01-12 13:57

    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.

    0 讨论(0)
提交回复
热议问题