Tanil
Tanil

Reputation: 348

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?

Upvotes: 2

Views: 65

Answers (3)

Ferchi
Ferchi

Reputation: 100

If you use jquery, you need to get the element, and put:

.attr("src");

or in tradicional javascript:

images[0].getAttribute("src");

this will gave you the exactly text in the html.

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237827

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.

Upvotes: 7

CodingIntrigue
CodingIntrigue

Reputation: 78525

Use getAttribute instead to get the raw value from the HTML:

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

jsFiddle Example

Upvotes: 2

Related Questions