When to use setAttribute vs .attribute= in JavaScript?

后端 未结 9 2323
闹比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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 12:41

    "When to use setAttribute vs .attribute= in JavaScript?"

    A general rule is to use .attribute and check if it works on the browser.

    ..If it works on the browser, you're good to go.

    ..If it doesn't, use .setAttribute(attribute, value) instead of .attribute for that attribute.

    Rinse-repeat for all attributes.

    Well, if you're lazy you can simply use .setAttribute. That should work fine on most browsers. (Though browsers that support .attribute can optimize it better than .setAttribute(attribute, value).)

提交回复
热议问题