Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery check if img has src

Tags:

jquery

image

src

I have a carousel of images that are dynamically populated. There is potential for up to 5 images, however, if there is less than 5 images I need to introduce some if statements in my code. Is it possible using jQuery to check if an img src is blank?

For example, if I have an image with class "optional" but it has no url, is there a way to detect this with jQuery?

<img class="optional" src="" />
like image 938
Sam Skirrow Avatar asked Oct 14 '13 13:10

Sam Skirrow


People also ask

How do I know if my IMG has an SRC?

Use the getAttribute() method to check if an image src is empty, e.g. img. getAttribute('src') . If the src attribute does not exist, the method returns either null or empty string, depending on the browser's implementation.

How add src attribute in jQuery?

Answer: Use the jQuery attr() Method You can use the attr() method to change the image source (i.e. the src attribute of the <img> tag) in jQuery. The following example will change the image src when you clicks on the image.

How to get and set the image SRC using jQuery?

To get the image src and set the image src using jQuery attr (). In this tutorial, you will learn how to get and set the image src using jQuery. The attr () method to get and change the image source in jQuery. Use the below script to get image src.

How to check if an image SRC is empty in HTML?

Use the getAttribute () method to check if an image src is empty, e.g. img.getAttribute ('src'). If the src attribute does not exist, the method returns either null or empty string, depending on the browser's implementation. Here is the HTML for the examples in this article. And here is the related JavaScript code.

How to change the image source in jQuery?

The attr() method to get and change the image source in jQuery. Get Image Src. Use the below script to get image src. $(document).ready(function() { $('.btn').click(function(){ $imgsrc = $('img').attr('src'); alert($imgsrc); }); }); Set the Image Src. Use the below script to set the image src.

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. Let’s first see how we can add jQuery −


2 Answers

Try this

$('.optional').each(function () {
    if (this.src.length > 0) {
        //if it has source
    }
});
like image 142
Anton Avatar answered Oct 03 '22 06:10

Anton


You can use attribute selector:

$('img.optional[src=""]');

In case that you want select the images that don't have empty src attributes:

$('img.optional[src!=""]');
like image 41
undefined Avatar answered Oct 03 '22 04:10

undefined