0

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

2

6 Answers 6

6

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'
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

are you missing brackets around 'this' ?
2

The attr method is the way to go:

$(".image").attr({
    src : "New image source",
    alt : "Alternative image text"
});

2 Comments

+1 for handling both attributes in one go! Just recently discovered that myself. Pretty neat stuff (:
Good stuff isn't it. I've only recently discovered it myself.
0
$("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");

2 Comments

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?
use the thing I described in this answer: adding a unique ID to each image tag.
0
$("img[src='small.jpg']").attr("src", "image/small.jpg")

Comments

0

You need the attr method:

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

Edit: see the docs for more information

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.