Many a time you might have come across a scenario where you would want to remove multiple attributes from an element. For example, consider the following DIV :
<div id="#rightSection" data-id="xyz" data-module="abc"> .... </div>
Now using jQuery’s removeAttr() method you want to remove both the data-id and data-module attributes. Many of us try to use multiple calls to the removeAttr() method by using jQuery’s chaining feature. Something like $(‘#rightSection’).removeAttr(‘data-id’).removeAttr(‘data-module’). However, while this may work, this is not a very optimal way to write the code.
So, How do I remove multiple attributes or How do I Combine multiple .removeAttr() statements?
The answer to that is very easy one. You can remove multiple attributes in jQuery by separating them using spaces. This means that you would have to pass all the attributes you want to remove, separated by space, to the removeAttr() method. So now your code should look similar to the following :
$("#rightSection").removeAttr('data-id data-module');
This way, you don’t have to repeat the .removeAttr() method to remove each attribute individually. And now you can actually Write Less and Do More 🙂 .
Do let us know if you liked the solution. Please like and share and help your friends to learn about this !