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="" />
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.
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.
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.
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.
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.
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 −
Try this
$('.optional').each(function () {
if (this.src.length > 0) {
//if it has source
}
});
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!=""]');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With