jQuery & DOM Manipulation

Working with Attributes

12 min Lesson 11 of 30

Working with Attributes

HTML attributes provide additional information about elements. jQuery makes it easy to read, modify, and remove attributes dynamically.

The .attr() Method

The .attr() method gets or sets attribute values for matched elements.

HTML:
<img id="logo" src="logo.png" alt="Company Logo" width="200">
<a id="website" href="https://example.com">Visit Website</a>
Getting Attributes:
// Get single attribute
var imgSrc = $("#logo").attr("src");
console.log(imgSrc); // "logo.png"

var linkHref = $("#website").attr("href");
console.log(linkHref); // "https://example.com"

// Non-existent attribute returns undefined
var title = $("#logo").attr("title");
console.log(title); // undefined
Setting Attributes:
// Set single attribute
$("#logo").attr("width", "300");
$("#website").attr("target", "_blank");

// Set multiple attributes
$("#logo").attr({
    src: "new-logo.png",
    alt: "New Company Logo",
    width: "250",
    height: "100"
});

The .removeAttr() Method

Use .removeAttr() to completely remove an attribute from elements.

HTML:
<input type="text" id="email" disabled required placeholder="Email">
JavaScript:
// Remove single attribute
$("#email").removeAttr("disabled");

// Remove multiple attributes (space-separated)
$("#email").removeAttr("disabled required");

// Now the input is enabled and no longer required

The .prop() Method

The .prop() method gets or sets properties (as opposed to attributes). Use it for boolean properties and element states.

HTML:
<input type="checkbox" id="terms" checked>
<input type="text" id="username" value="JohnDoe">
<button id="submit" disabled>Submit</button>
JavaScript:
// Get properties
var isChecked = $("#terms").prop("checked");
console.log(isChecked); // true

var isDisabled = $("#submit").prop("disabled");
console.log(isDisabled); // true

// Set properties
$("#terms").prop("checked", false);      // Uncheck
$("#submit").prop("disabled", false);    // Enable button

// Toggle property
var current = $("#terms").prop("checked");
$("#terms").prop("checked", !current);
When to use .attr() vs .prop():
  • Use .attr() for HTML attributes: src, href, class, id, data-*, title
  • Use .prop() for element properties: checked, disabled, selected, value
  • For boolean attributes, .prop() returns true/false while .attr() returns attribute value or undefined

The .removeProp() Method

Use .removeProp() to remove properties. However, this is rarely needed and can cause issues with native properties.

JavaScript:
// Add custom property
$("#username").prop("customProp", "customValue");

// Remove custom property
$("#username").removeProp("customProp");

// WARNING: Never remove native properties
// $("#username").removeProp("disabled"); // DON'T DO THIS!
Warning: Never use .removeProp() on native properties like disabled, checked, or selected. Use .prop(propertyName, false) instead.

Using Callback Functions

Both .attr() and .prop() accept callback functions for dynamic attribute assignment.

HTML:
<img class="thumbnail" src="img1.jpg">
<img class="thumbnail" src="img2.jpg">
<img class="thumbnail" src="img3.jpg">
JavaScript:
// Add unique ID to each image
$(".thumbnail").attr("id", function(index) {
    return "img-" + (index + 1);
});

// Update src based on current value
$(".thumbnail").attr("src", function(index, currentSrc) {
    return currentSrc.replace(".jpg", "-large.jpg");
});

// Conditional attributes
$(".thumbnail").attr("loading", function(index) {
    return index < 3 ? "eager" : "lazy";
});

Practical Example: Image Gallery with Lightbox

HTML:
<div class="gallery">
    <img src="thumb1.jpg" data-full="full1.jpg" alt="Photo 1">
    <img src="thumb2.jpg" data-full="full2.jpg" alt="Photo 2">
    <img src="thumb3.jpg" data-full="full3.jpg" alt="Photo 3">
</div>

<div id="lightbox" style="display: none;">
    <img id="lightbox-img" src="" alt="">
    <button id="close-lightbox">Close</button>
</div>
JavaScript:
$(document).ready(function() {
    // Add cursor pointer and title to thumbnails
    $(".gallery img").attr({
        "style": "cursor: pointer;",
        "title": "Click to view full size"
    });

    // Open lightbox on thumbnail click
    $(".gallery img").click(function() {
        var fullSrc = $(this).attr("data-full");
        var alt = $(this).attr("alt");

        $("#lightbox-img").attr({
            src: fullSrc,
            alt: alt
        });

        $("#lightbox").show();
    });

    // Close lightbox
    $("#close-lightbox").click(function() {
        $("#lightbox").hide();
        $("#lightbox-img").attr("src", ""); // Clear image
    });

    // Close on background click
    $("#lightbox").click(function(e) {
        if (e.target.id === "lightbox") {
            $(this).hide();
        }
    });
});

Form Validation Example

HTML:
<form id="signup-form">
    <input type="email" id="email" placeholder="Email">
    <input type="password" id="password" placeholder="Password">
    <input type="checkbox" id="agree"> I agree to terms
    <button type="submit" id="submit-btn" disabled>Sign Up</button>
</form>
JavaScript:
$(document).ready(function() {
    // Check form validity on input
    $("#email, #password, #agree").on("input change", function() {
        var email = $("#email").val();
        var password = $("#password").val();
        var agreed = $("#agree").prop("checked");

        // Enable submit if all conditions met
        var isValid = email.length > 0 &&
                      password.length >= 6 &&
                      agreed;

        $("#submit-btn").prop("disabled", !isValid);

        // Add visual feedback
        if (isValid) {
            $("#submit-btn").attr("title", "Click to submit");
        } else {
            $("#submit-btn").attr("title", "Complete all fields");
        }
    });

    // Handle form submission
    $("#signup-form").submit(function(e) {
        e.preventDefault();

        // Disable form during submission
        $("#signup-form input, #signup-form button").prop("disabled", true);
        $("#submit-btn").attr("value", "Submitting...");

        // Simulate API call
        setTimeout(function() {
            alert("Form submitted successfully!");
            $("#signup-form")[0].reset();
            $("#signup-form input, #signup-form button").prop("disabled", false);
            $("#submit-btn").prop("disabled", true);
        }, 1500);
    });
});
Exercise:
  1. Create a dynamic link manager that allows users to input a URL and link text
  2. Generate an anchor tag with the href and text content
  3. Add a checkbox to control whether the link opens in a new tab (target="_blank")
  4. Add another checkbox to add rel="nofollow" for SEO
  5. Display the generated HTML code and a preview of the clickable link

Common Attributes Reference

Attribute Used On Description
href <a>, <link> URL destination
src <img>, <script> Source file path
alt <img> Alternative text
title All elements Tooltip text
disabled Form elements Disables interaction
placeholder <input>, <textarea> Hint text
value Form elements Current value

Summary

  • .attr(name) - Get attribute value
  • .attr(name, value) - Set attribute value
  • .attr(object) - Set multiple attributes
  • .removeAttr(name) - Remove attribute
  • .prop(name) - Get property value (use for boolean properties)
  • .prop(name, value) - Set property value
  • Use .attr() for HTML attributes, .prop() for DOM properties
  • Callback functions enable dynamic attribute assignment

ES
Edrees Salih
18 hours ago

We are still cooking the magic in the way!