jquery
  1. jquery-attr

JQuery attr()

The attr() method in jQuery is used to get or set the value of an attribute for a selected element.

Syntax

The syntax to get the value of an attribute using attr() method is:

$(selector).attr(attributeName);

The syntax to set the value of an attribute using attr() method is:

$(selector).attr(attributeName, value);

Use

The attr() method is useful when you need to get or set the value of an attribute for an HTML or XML element. It can be used for a variety of purposes, such as adding or removing a class attribute, changing the src of an img element, or setting the title of a link element.

Example

Here is an example of using attr() method to get and set the value of an attribute:

In this example, we use the attr() method to change the src attribute of an img element when the button is clicked. We first select the img element using the #myImage selector, and then use the attr() method to set the value of the src attribute to the new image path.

Summary

The attr() method in jQuery is a useful tool to get or set the value of an attribute for an element. It can be used for a variety of purposes, such as adding or removing a class attribute, changing the src of an img element, or setting the title of a link element. It provides an easier and more efficient way to work with attributes in HTML or XML documents.

<!DOCTYPE html>
<html>
<head>
    <title>JQuery attr() Example</title>
</head>
<body>

    <img id="myImage" src="https://static.additionalsheet.com/images//others/lucy.jpg" alt="My image" />

    <button onclick="changeImage()">Change Image Attribute</button>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        function changeImage() {
            var newSrc = "https://static.additionalsheet.com/images//others/alisa.jpg";
            $("#myImage").attr("src", newSrc);
        }
    </script>
</body>
</html>
Try Playground
Published on: