jQuery Attributes — Complete Guide to .attr(), .prop(), and .removeAttr()
In this tutorial, you will learn about jquery attributes. We cover key concepts, practical examples, and best practices to help you master this topic.
jQuery attribute methods let you read and write HTML attributes and DOM properties, managing element state like IDs, classes (partial), hrefs, srcs, checked state, and disabled state.
What You'll Learn
- Reading and setting HTML attributes with .attr()
- Using .prop() for boolean DOM properties
- Difference between .attr() and .prop()
- Removing attributes and properties
- Callback functions for dynamic attribute values
Why It Matters
Attributes control how elements behave and appear: links need correct hrefs, images need srcs, form elements need checked/disabled state. Using the right method (.attr vs .prop) prevents subtle bugs.
Real-World Use
A product gallery where clicking a thumbnail updates the main image's src attribute, a form where checking a box enables the submit button via disabled property, and a dynamic menu where links get their hrefs from a data source.
Attribute vs Property Flow
flowchart LR
A[HTML Attribute] --> B[.attr()]
C[DOM Property] --> D[.prop()]
B --> E[HTML Source]
D --> F[Element State]
E --> G[Initial Value]
F --> H[Current Value]
style D fill:#e6f3ff,stroke:#4a90d9,stroke-width:2px
.attr() — Get and Set Attributes
// Get an attribute value
var src = $('img').attr('src');
console.log('Image source:', src);
// Set a single attribute
$('img').attr('alt', 'Product photo');
// Set multiple attributes
$('a').attr({
href: 'https://example.com',
title: 'Visit Example',
target: '_blank'
});
// Set using a callback function
$('a').attr('href', function(index, currentHref) {
return currentHref + '?ref=homepage';
});
Expected output: The .attr() getter returns the attribute value as a string. The setter updates the attribute in the DOM, which is reflected in the HTML source.
.prop() — Get and Set DOM Properties
// Get a property
var isChecked = $('#agree').prop('checked');
var isDisabled = $('#submit-btn').prop('disabled');
// Set properties
$('#agree').prop('checked', true);
$('#submit-btn').prop('disabled', true);
// Set multiple properties
$('input').prop({
required: true,
readOnly: false,
indeterminate: false
});
// Property with callback
$('select option').prop('selected', function() {
return $(this).val() === 'preferred';
});
Expected output: .prop() manages the element's JavaScript property state. checked returns a boolean (true/false), not a string like the HTML attribute does.
.attr() vs .prop() — When to Use Which
// BAD: Using .attr() for boolean properties
if ($('#checkbox').attr('checked') !== undefined) { /* ... */ }
// GOOD: Using .prop() for boolean properties
if ($('#checkbox').prop('checked')) { /* ... */ }
// BAD: Using .prop() for custom HTML attributes
$('div').prop('data-id', 42); // Does not set the HTML attribute
// GOOD: Using .attr() for custom HTML attributes
$('div').attr('data-id', 42); // Sets data-id="42" in the HTML
// Key differences:
// .attr('checked') returns 'checked' or undefined (strings)
// .prop('checked') returns true or false (booleans)
// .attr('href') returns the literal value '/page'
// .prop('href') returns the full URL 'https://site.com/page'
When to Use Each
| Scenario | Use | Reason |
|---|---|---|
| Custom data attributes | .attr() | HTML attributes are meant for this |
| Standard attributes (id, class, href) | .attr() | Reflects the HTML source |
| Checked state | .prop() | Boolean DOM property |
| Disabled state | .prop() | Boolean DOM property |
| Selected option | .prop() | Boolean DOM property |
| href value | .prop() if full URL needed | .prop() resolves the full URL |
| tabIndex | .prop() | Numeric DOM property |
.removeAttr() and .removeProp()
// Remove an HTML attribute
$('input').removeAttr('disabled');
$('img').removeAttr('onerror');
// Remove a DOM property
$('input').removeProp('required');
// Note: .removeProp() removes the property entirely
// .removeAttr() sets the attribute to its default value
$('input[type="checkbox"]').removeAttr('checked'); // Unchecks
$('input[type="checkbox"]').removeProp('checked'); // Also works
Working with Data Attributes
// Set data attributes
$('.card').attr('data-id', 123);
$('.card').attr('data-category', 'premium');
// Get data attributes
var id = $('.card').attr('data-id');
// Using jQuery's .data() method (caches value)
$('.card').data('id', 456); // Sets in jQuery cache
console.log($('.card').attr('data-id')); // Still 123 (not updated)
// To update both data cache and HTML attribute:
$('.card').attr('data-id', 789);
console.log($('.card').data('id')); // Now 789 (re-read from DOM)
Toggle Boolean Properties
// Toggle disabled state
$('#submit-btn').prop('disabled', function(i, currentDisabled) {
return !currentDisabled;
});
// Toggle checked state
$('#select-all').click(function() {
$('.item-checkbox').prop('checked', function() {
return $(this).prop('checked') === false;
});
});
Expected output: The callback receives the current value and returns the new value. For boolean properties, returning !currentDisabled toggles the state.
Common Mistakes
Using .attr() for checked/disabled -
.attr('checked')returns the string 'checked' or undefined, not true/false. Use .prop() for boolean properties.Assuming .attr() and .prop() return the same href -
.attr('href')returns the literal attribute value ('/page')..prop('href')returns the fully resolved URL ('https://site.com/page').Using .removeProp() on native properties - Removing native properties like 'checked' or 'disabled' removes them from the JavaScript object entirely, which may cause unexpected behavior. Use .removeAttr() instead.
Not using callback for dynamic values - Callbacks in .attr() and .prop() let you compute the new value based on the index or current value, avoiding manual loops.
Confusing .data() with .attr('data-*') -
.data()caches values and reads them only once from the DOM. Subsequent writes via.data()do not update the HTML attribute.
Practice Questions
- What is the difference between .attr() and .prop()?
- When would you use .prop() instead of .attr() for a checkbox?
- How do you set multiple attributes at once?
- What does .attr('href') return compared to .prop('href')?
- How do you remove a data attribute from an element?
Challenge: Build a form where checking "Select All" toggles all checkbox .prop('checked') states, and the "Submit" button's disabled property updates based on whether at least one checkbox is checked.
FAQ
Mini Project
Build a theme customizer panel where users can change colors, font sizes, and spacing via sliders. Use .attr() to update the href of the theme stylesheet link, .prop() to toggle feature flags, and .data() to store user preferences.
What's Next
Attributes store data on elements. Learn how to manage data with .data() for Caching values and attaching custom data to DOM elements.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro