Search

Get and Set attribute value using jQuery attr method

post-title

jQuery attr() method is used to get first selected element or set attribute value to matched all elements.

Syntax:

Get current attribute value for first matched content:

$(selector).attr(attribute);

Set the new attribute and value to all matched elements:

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

Set multiple new attribute and value to all matched elements:

$(selector).attr({attribute:value, attribute:value...});

Parameters:

attribute is attribute name of element
value  attribute value to set on element

Below example shows how to get images source link using button click.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <img src="https://laravelcode.com/assets/images/logo.png" alt="laravelcode" />
    <button>Get image link</button>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('button').click(function() {
                var link = $('img').attr('src');
                alert(link);
            });
        });
    </script>
</body>
</html>

If you want to change or add new attribute, pass the second parameter as attribure value.

Here is the example to change image changing src value.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <img src="https://laravelcode.com/assets/images/logo.png" alt="laravelcode" /><br>
    <button>Get image link</button>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('button').click(function() {
                $('img').attr('src', 'https://laravelcode.com/images/password-generator.jpg');
            });
        });
    </script>
</body>
</html>

If you want to change multiple attribute value to all matched elements, pass them to json object.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <img src="https://laravelcode.com/assets/images/logo.png" title="laravelcode" /><br>
    <button>Get image link</button>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('button').click(function() {
                $('img').attr({src:'https://laravelcode.com/images/password-generator.jpg', title: 'Password generator', width: '200px'});
            });
        });
    </script>
</body>
</html>

I hope it will help you.