How to Add and Remove Attributes with jQuery
In this tutorial, we will learn how to add attributes to elements, modify and remove them with jQuery.
Add an Attribute
The easiest way to add an attribute to an element with jQuery is to use the prop()
method. Pass the name of the attribute as the first argument and the value as the second.
<div id="bar" class="active"></div>
<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
$('#bar').prop('class', 'active');
});
In the above example, a class
attribute is added to an element with a value of "active" when a button is clicked.
Changing the Value of an Attribute
To change the value of an attribute supply a new value using prop()
.
<input type="text" name="bar" id="bar" class="active">
<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
$('#bar').prop('class', 'disabled').prop('disabled', true);
});
In the example above, the class
attribute is changed to disabled and a disabled
attribute is added to an input element.
Remove an Attribute
To remove an attribute completely from an element use the removeAttr()
method, supplying the name of the attribute to remove.
<input type="text" name="bar" id="bar" disabled>
<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
$('#bar').removeAttr('disabled');
});
In the above example, the disabled
attribute is removed from the input
element.
If the goal is to set an attribute value to false, don't use removeAttr()
, instead, update the attribute value using prop()
.
<input type="text" name="bar" id="bar" disabled>
<button type="button" id="foo">Click me</button>
$('#foo').click(function() {
$('#bar').prop('disabled', false);
});