When to use setAttribute vs .attribute= in JavaScript?

后端 未结 9 2325
闹比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:38

    One case I found where setAttribute is necessary is when changing ARIA attributes, since there are no corresponding properties. For example

    x.setAttribute('aria-label', 'Test');
    x.getAttribute('aria-label');
    

    There's no x.arialabel or anything like that, so you have to use setAttribute.

    Edit: x["aria-label"] does not work. You really do need setAttribute.

    x.getAttribute('aria-label')
    null
    x["aria-label"] = "Test"
    "Test"
    x.getAttribute('aria-label')
    null
    x.setAttribute('aria-label', 'Test2')
    undefined
    x["aria-label"]
    "Test"
    x.getAttribute('aria-label')
    "Test2"
    

提交回复
热议问题