jQuery

jQuery - Add, Change & Remove Attributes

Add, modify, and remove HTML attributes with jQuery using .attr(), .removeAttr(), .addClass(), and .toggleClass().

Add & Change Attributes with .attr()

// Set a single attribute
$('img').attr('alt', 'Product photo');
$('a').attr('href', 'https://example.com');

// Set multiple attributes
$('#avatar').attr({
  src: 'user-photo.jpg',
  alt: 'User avatar',
  width: 100,
  height: 100
});

// Change attribute based on current value
$('a').attr('href', function(i, oldHref) {
  return oldHref + '?ref=sidebar';
});

Remove Attributes with .removeAttr()

// Remove single attribute
$('input').removeAttr('disabled');
$('a').removeAttr('target');

// Remove multiple (space-separated)
$('input').removeAttr('readonly required');

// Common pattern: toggle disabled state
$('#submit').attr('disabled', 'disabled');  // disable
$('#submit').removeAttr('disabled');         // enable

// Better for boolean props - use .prop()
$('#submit').prop('disabled', true);
$('#submit').prop('disabled', false);

Class Manipulation

// Add a class
$('.card').addClass('active');
$('.card').addClass('highlight bordered');  // multiple

// Remove a class
$('.card').removeClass('active');

// Toggle a class
$('.menu').toggleClass('open');

// Check if element has a class
if ($('.card').hasClass('active')) {
  console.log('Card is active');
}

// Conditional class based on callback
$('tr').addClass(function(index) {
  return index % 2 === 0 ? 'even-row' : 'odd-row';
});

Data Attributes

// Set data attribute (HTML attribute)
$('#item').attr('data-price', '29.99');
$('#item').attr('data-category', 'electronics');

// Read with .data() - auto-parses types
var price = $('#item').data('price');  // 29.99 (number)

// Set with .data() - only in jQuery cache, NOT in DOM
$('#item').data('price', 39.99);

// To update the actual HTML attribute:
$('#item').attr('data-price', '39.99');

Practical Examples

// Image lazy loading
$('img[data-src]').each(function() {
  $(this).attr('src', $(this).data('src'));
  $(this).removeAttr('data-src');
});

// Dynamic form validation styling
$('input').on('blur', function() {
  if ($(this).val() === '') {
    $(this).addClass('error').attr('aria-invalid', 'true');
  } else {
    $(this).removeClass('error').removeAttr('aria-invalid');
  }
});

// External link handler
$('a[href^="http"]').attr({
  target: '_blank',
  rel: 'noopener noreferrer'
}).addClass('external-link');

Vanilla JavaScript Equivalents

jQueryVanilla JS
.attr('src', 'x')el.setAttribute('src', 'x')
.removeAttr('src')el.removeAttribute('src')
.addClass('x')el.classList.add('x')
.removeClass('x')el.classList.remove('x')
.toggleClass('x')el.classList.toggle('x')
.hasClass('x')el.classList.contains('x')

Last updated: 2026 • Browse all courses