When to use setAttribute vs .attribute= in JavaScript?

后端 未结 9 2322
闹比i
闹比i 2020-11-22 11:44

Has a best-practice around using setAttribute instead of the dot (.) attribute notation been developed?

E.g.:

myObj.setAttr         


        
9条回答
  •  孤城傲影
    2020-11-22 12:36

    methods for setting attributes(for example class) on an element: 1. el.className = string 2. el.setAttribute('class',string) 3. el.attributes.setNamedItem(object) 4. el.setAttributeNode(node)

    I have made a simple benchmark test (here)

    and it seems that setAttributeNode is about 3 times faster then using setAttribute.

    so if performance is an issue - use "setAttributeNode"

提交回复
热议问题