What are the benefits of using attr() instead of using addClass() in jquery?
What are the benefits of using attr() instead of using addClass() in jquery?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
When you use
attrmethod to set the class of any element it will override the existing class name with whatever value you pass as the second argument toattrmethod.Where as if you use
addClassmethod 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 giveWhere as using
$('#div1').addClass('newClass')will giveSo it is always adviseable to use
addClass/removeClassto manupulate classes of html elements using jQuery. But at the end it depends on your requirement what to use when.