Add and remove attribute in jQuery

By Faruque Ahamed Mollick

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:



$("p").attr("id","myId");

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:

$("p").attr({"id":"myId", "class":"myClass"});

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:
    $(selector).attr(attribute,value);
  • Add multiple attributes to an animal:
    $(selector).attr({attribute1:value1, attribute2:value2});

 

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:

$("p").removeAttr("id");

In the above code, we have removed the ID from our element.

Below is the syntax to remove attribute using jQuery removeAttr() method:

$(selector).removeAttr(attribute);

 

Also, read:

 

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.

 

Leave a Reply

Your email address will not be published. Required fields are marked *