How to remove multiple attributes in jquery?

Posted underjQuery

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 !

TaggedattributeJavascriptjQueryJquery API – Read tutorials related to JavaScript, jQuery, HTML5, CSS3 and more !

Cover Image for How to check if checkbox is checked in jQuery?

How to check if checkbox is checked in jQuery?

It is very easy to check if a checkbox is checked in jQuery using the .is() or .prop() method of jQuery combined with the ‘:checked’ selector. There are other ways too like checking for the attribute checked value, however, they aren’t very reliable. The easiest and most stable way to check if checkbox is checked … Read more

Cover Image for [Solved] Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’

[Solved] Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’

You might be facing an “Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’ ” error if you are using the react-router-dom package version 6. This error is caused due to using the older switch syntax of the react-router-dom. From version 6 onwards, the react-router-dom has replaced “Switch” with “Routes”. Let us take a look … Read more