Benefits of using attr() over addClass in jquery

后端 未结 5 1669
野性不改
野性不改 2020-12-03 08:07

What are the benefits of using attr() instead of using addClass() in jquery?

5条回答
  •  情歌与酒
    2020-12-03 09:06

    When you use attr method to set the class of any element it will override the existing class name with whatever value you pass as the second argument to attr method.

    Where as if you use addClass method to add any class to an element it will just add the class and also retain the existing classes. If the class to add already exists then it will just ignore it.

    E.g.

    Using $('#div1').attr('class', 'newClass') will give

    Where as using $('#div1').addClass('newClass') will give

    So it is always adviseable to use addClass/removeClass to manupulate classes of html elements using jQuery. But at the end it depends on your requirement what to use when.

提交回复
热议问题