Add and Remove Attribute with jQuery
This jQuery helps to add and remove attributes with jQuery. jQuery provides the attr()
method for dynamically adding attributes to HTML elements. The attr()
method is a powerful tool for manipulating attributes of HTML elements in a jQuery context.
jQuery attr()
The jQuery attr() method is used to get or set attributes of HTML elements. It can be used for both reading and modifying attributes.
The .attr()
method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop()
method.
You can also check other tutorial of Datatable,
Add and Remove Attributes Using jQuery
I need to include an ID
attribute in an HTML button element. Here's a basic explanation of how it works:
<button class="add">Add</button> <button class="remove">Remove</button
We click the 'Add'
button, it will append an ID
attribute to the HTML element. Conversely, the 'Remove'
button will eliminate the ID
attribute from the HTML element.
How To Add Attribute Using jQuery
Let’s add attributes to an element using attr()
method.
The Syntax:
$("element").attr("attributeName", "newValue");
The below code snippet below demonstrates attribute addition into html using jquery.
$(".add").click(function(){ $("#name").removeAttr("id"); });
It will set the value of the specified attribute for the selected HTML element. For example, to set the “id” attribute of a ‘name’ class element:
How To Remove Attributes Using jQuery
To remove an attribute from an element, you can use the removeAttr()
method:
The Syntax:
$("element").removeAttr("attributeName");
The code snippet below demonstrates attribute removal:
$(".remove").click(function(){ $("#name").removeAttr("id"); });
To remove the “disabled” attribute from a button element:
$("button").removeAttr("disabled");
Modifying Multiple Attributes
You can also modify multiple attributes at once by passing an object to the attr()
method. For example:
$("element").attr({ attributeName1: "value1", attributeName2: "value2" });
Originally published at https://www.js-tutorials.com on September 3, 2023.