Add and remove attribute in jQuery
In this post, we are going to learn how to add an remove attribute in jQuery from an element.
Adding and removing attribute to an element is quite easy. Here I am going to show you the example with the syntax of jQuery method that will be used to add and remove attribute in jQuery.
Add attribute in jQuery
Let’s first see how to add an attribute to an element in jQuery.
jQuery already has a method which is attr() method. Using this method, we can add an attribute to an element with just one line of jQuery code that is given below:
In the above code, we have added an ID as the attribute to an HTML paragraph element. We can leave the attribute value empty if we don’t need it.
We can also add multiple attributes with values just like you can see below:
You can see that we have added both ID and class to the paragraph element using jQuery attr() method. We did it just with one lines of code.
Now take a look to the syntax of jQuery attr() method to remove attribute from an HTML element:
- Add only one attribute to the element:
- Add multiple attributes to an animal:
Remove attribute in jQuery
Now its time to remove attribute in jQuery.
We can also remove attribute easily from an element just within a line of code.
jQuery has removeAttr() method that can remove an attribute from an element. Below is the jQuery code that can remove an attribute from an element:
In the above code, we have removed the ID from our element.
Below is the syntax to remove attribute using jQuery removeAttr() method:
So we have learned how to add and remove attribute in jQuery. I hope this post will be helpful to you and you will be able to implement it in your work.