Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the source of an Image - not the standard way

Using Javascript;

I have an image src for example src = "images/folder1/image1.jpg"

The src folder exists in a gallery section of the website at "http://www.example.com/gallery/index.php"

The full image src when I use

var images = doucment.getElementsByTagName("img");
var source = images[0].src;

this outputs: "http://www.example.com/gallery/images/folder1/image1.jpg"

I want it to output: "images/folder1/image1.jpg"

Is this possible using regExp or an equivalent? If so how?

like image 534
Tanil Avatar asked Dec 19 '25 14:12

Tanil


1 Answers

This is one of those occasions where there is a difference between an HTML element's attributes and its properties.

Attributes are (generally speaking) the values specified in the HTML. Properties are the attribute values standardised to be consistent (e.g. relative URLs are transformed into absolute URLs). Generally it's more useful to work with properties, but on this occasion you want the attribute value.

To do this, we use the getAttribute method:

var source = images[0].getAttribute('src');

This gets the value specified in the HTML, rather than the computed value used in the DOM.

like image 97
lonesomeday Avatar answered Dec 21 '25 02:12

lonesomeday



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!