Changing Attributes
Learn how to get, set, and remove HTML attributes using jQuery.
jQuery makes it easy to read, change, and remove HTML attributes on any element.
attr() — Get and Set Attributes
// Get an attribute
let link = $("a").attr("href");
let imgSrc = $("img").attr("src");
console.log(link, imgSrc);
// Set an attribute
$("a").attr("href", "https://example.com");
$("img").attr("alt", "Product image");
// Set multiple attributes at once
$("img").attr({
src: "new-image.jpg",
alt: "Updated image",
title: "Click to enlarge"
});
removeAttr() — Remove an Attribute
$("a").removeAttr("target");
$("input").removeAttr("disabled");
prop() — For Boolean Properties
Use prop() for boolean properties like checked, disabled, selected:
// Check a checkbox
$("input[type='checkbox']").prop("checked", true);
// Disable a button
$("#submitBtn").prop("disabled", true);
// Read the state
let isChecked = $("#agree").prop("checked");
console.log(isChecked); // true or false
attr() vs prop()
attr()— works with HTML attributes (href, src, class, id)prop()— works with DOM properties (checked, disabled, selected)
val() — Form Input Values
// Get value
let username = $("input[name='username']").val();
// Set value
$("input[name='email']").val("user@example.com");
// Get selected option text
let selected = $("select option:selected").text();
data() — Custom Data Attributes
// HTML: <div data-user-id="42" data-role="admin">
let userId = $("div").data("user-id"); // 42
let role = $("div").data("role"); // "admin"
// Set data
$("div").data("status", "active");