rdmdk
rdmdk

Reputation: 15

Remove filepaths from multiple image elements in HTML using jQuery

I'm trying to keep the filenames but remove the filepaths from the image elements on my page, and I've managed to figure out the following based on what I've already gathered from similar questions.

I'm able to remove just the filepaths, but I can't figure out why the source of the first image is being copied into the other two images.


Here's what I've put together so far

HTML

<img src="/path/to/image.gif" />
<img src="/different/path/to/picture.jpg" />
<img src="another/path/to/graphic.png" />

JS

var abc = $('img').attr('src');
var def = abc.split('/').pop();

$('img').attr('src', def);

RESULT

<img src="image.gif">
<img src="image.gif">
<img src="image.gif">

http://jsfiddle.net/aztdeu0w/

Upvotes: 0

Views: 88

Answers (2)

bvaughn
bvaughn

Reputation: 13487

This is how jQuery works. The $ selector grabs an array of items (containing 0-N matched elements) and then applies your operations to those elements. For some operations though- read operations like attr('src') it only makes sense to read a single item, so it reads the first one.

What you want is to iterative over the images and apply your regex to them one at a time. So...

$('img').each(function(index, item){
  // Read/write attr here
});

Upvotes: 0

taxicala
taxicala

Reputation: 21769

You arent iterating through all the img elements, try the following:

$('img').each(function(){
    var imgName = $(this).attr('src').split('/').pop();
    $(this).attr('src', imgName);
});

That way you will loop through all the images and replace accordingly the src attribute.

Upvotes: 2

Related Questions