How to get the value of src attribute in jQuery?

To get the value of src attribute in jQuery is quite easy. We will get the src attribute of the img tag. This attribute has the URL of the image and can be retrieved using jQuery's attr() method.

The attr() method in jQuery is used to get the value of an attribute for the first element in the set of matched elements. When we pass 'src' as a parameter to this method, it returns the source URL of the image.

Example

You can try to run the following code to learn how to get the value of src attribute in jQuery ?

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            // Get the src attribute value of the image
            var imageSrc = $('#myimg').attr('src');
            alert('Image source: ' + imageSrc);
            
            // You can also display it in the paragraph
            $('#result').text('Image source: ' + imageSrc);
        });
    </script>
</head>
<body>
    <img src="https://via.placeholder.com/150x100/4CAF50/FFFFFF?text=Logo" id="myimg" alt="Sample Logo">
    <p>Logo</p>
    <p id="result"></p>
</body>
</html>

The output of the above code is ?

An alert box will display: "Image source: https://via.placeholder.com/150x100/4CAF50/FFFFFF?text=Logo"
The paragraph with id "result" will show the same text on the webpage.

In this example, we use $('#myimg').attr('src') to select the image element with ID "myimg" and retrieve its src attribute value. The $(document).ready() function ensures that the jQuery code runs after the DOM is fully loaded.

Conclusion

Getting the src attribute value in jQuery is straightforward using the attr('src') method. This technique is useful for dynamically accessing image URLs in web applications.

Updated on: 2026-03-13T17:47:55+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements