tags:

views:

182

answers:

6

Hi all,

I have a bit of an issue here. As Im new to jQuery this will probable will sound simple for you.

I need to add path to alt and change the alt so it will have extension .jpg and screen within jquery

So how can I transfer this

<img src="small.jpg" class="image"  alt="big01">

into this:

<img src="/image/small.jpg" class="image"  alt="/image/big01.jpg">

I forgot to add: I need to fish out image name and then add path to that image as this will change as there is many on the site. Not sure if I made myself clear Any ideas please?

Many Thanks for your help in advance

A: 

You need the attr method:

$('img.image').attr('alt', '/image/big01.jpg').attr('src','/image/small.jpg');

Edit: see the docs for more information

spmason
A: 
$("img").attr("src", "/image/small.jpg").attr("alt", "/image/big01.jpg");

The above will work on all images, but to get direct access to your specific image give it an id and address it like this:

<img id="myimg" src="...

$("#myimg").attr("src", "/image/small.jpg").attr("alt", "/image/big01.jpg");
Makram Saleh
This is grat guys, but i forgot to add that I need to fish out image name as this will change as there is many on the site. Any ideas please?
Dom
use the thing I described in this answer: adding a unique ID to each image tag.
Makram Saleh
A: 
$("img[src='small.jpg']").attr("src", "image/small.jpg")
David Parunakian
+2  A: 

The attr method is the way to go:

$(".image").attr({
    src : "New image source",
    alt : "Alternative image text"
});
Kieron
+1 for handling both attributes in one go! Just recently discovered that myself. Pretty neat stuff (:
peirix
Good stuff isn't it. I've only recently discovered it myself.
Kieron
+4  A: 

My first question would be, why aren't those paths in the img tag already?

If you need all img tags to be updated to include that information. First, you need to loop through all the img elements. This is simply: $("img").each( functions here)

From here, you can do as some others have pointed out and get the attributes using the attr method and then alter them.

$("img").each( function(){
  $(this).attr({
     src: '/image/' + $(this).attr('src'),
     alt: '/image/' + $(this).attr('alt') + '.jpg'
  });
});
Anthony Potts
are you missing brackets around 'this' ?
Tom Haigh
Edited, thank you, Tom.
Anthony Potts
A: 

I know you won't want to hear this, but you're not using the alt tag correctly. Alt is there to explain to less accessible web users (ie Someone with a screen reader) what your image is actually showing.

If you are using it to store an image you're toggling between, can i suggest you just make your own custom attribute. Something like altImage would work perfectly.

Evildonald