How to Remove an Attribute in jQuery

Removing an attribute from an HTML element using jQuery is a common task in web development, typically accomplished with the removeAttr() method. This article covers the syntax and implementation of removeAttr(), demonstrates how to remove single or multiple attributes, and explains when to use property manipulation instead for boolean attributes.

The removeAttr() Method

The primary and most efficient way to delete an attribute from a DOM element using jQuery is the .removeAttr() method. It targets the selected elements and strips away the specified attribute completely.

Basic Syntax

$(selector).removeAttr(attributeName);
  • selector: The jQuery selector targeting the HTML element(s).
  • attributeName: A string representing the name of the attribute you want to remove (e.g., title, target, disabled).

Example: Removing a Single Attribute

If you have a link with a target="_blank" attribute and want to remove it dynamically:

<a id="myLink" href="https://example.com" target="_blank">Visit Site</a>

You can remove the target attribute with the following code:

$('#myLink').removeAttr('target');

After execution, the element becomes <a id="myLink" href="https://example.com">Visit Site</a>.


Removing Multiple Attributes

Starting with jQuery 1.7, you can remove multiple attributes at once by separating their names with a space inside the string parameter.

Example: Removing Multiple Attributes Simultaneously

<input type="text" id="username" disabled="disabled" readonly="readonly" title="Username Field">
$('#username').removeAttr('disabled readonly title');

This single line strips the disabled, readonly, and title attributes from the input element.


Attributes vs. Properties (Boolean Values)

For boolean attributes like checked, disabled, or selected, removing the attribute using removeAttr() works, but it can sometimes cause unexpected behavior across different browsers when working with dynamic form states.

In modern jQuery (1.6+), it is often recommended to use .prop() instead of .removeAttr() to toggle these states:

// Preferred for enabling an element
$('#submitBtn').prop('disabled', false);

// Preferred for unchecking a checkbox
$('#agreeCheckbox').prop('checked', false);

Use removeAttr() when you need to completely eliminate the attribute from the HTML markup (such as style, data-*, href, or title), and use prop() when managing the current dynamic state of form controls.