Get src image without uploading image?
I have an html fragment returned via ajax. This snippet is an <img> .
<img src="image.jpg" /> I need to extract the value of the src attribute without first loading the image. The reason for this is the src attribute, which contains a partial path that I need to manipulate in the application to load the image correctly.
I have the following code currently retrieving the src attribute:
var src = $(value).attr('src'); However, this leads to an image loading, which leads to 404. I would like to avoid this unnecessary request.
How to extract the value of the src attribute without causing the browser to load the image?
You can simply delete the attribute after accessing it.
This will not load an invalid image, as you can confirm in your console:
var s= $('<img src="invalidURL.jpg">'), src= s.attr('src'); s.removeAttr('src'); console.log(src); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Remove removeAttr() and it will try to load the image.
It is probably best to display a data tag on the image. Then you can manipulate this with jQuery and then use it to write the final path of the image.
So, you would do something similar in your HTML:
<img data-img-src="abc.jpg" class="my-image" /> Then in your jQuery:
var path = $('.my-image').data('img-src'); console.log(path); // Do something here, then write the new path with: $('.my-image).attr('src', new_path); EDIT: Sorry, I just re-read the bit where it appeared through AJAX. In this case, you can probably use the data callback of your ajax request to remove src from the image.