2

I have some images on my page, but they're all the same image. I'd like to know how I can change them all with jQuery. Below is what I currently have setup.

I have each image with an ID like image-1, image-2, etc. and to change them I use

$("#image-1").attr({src:"..."});
$("#image-2").attr({src:"..."});

Is there a way I can just set my ID to myTag and then change the image src for every image with that id? Because if I were to do this when the method i have now, it'll only change the first image with that id.

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
Kyle Colantonio
  • 454
  • 1
  • 3
  • 21
  • 2
    Can you instead apply a class to the images, to group them all together? – Ming Nov 20 '13 at 00:53
  • 2
    "every image with that ID" - IDs should really be unique, even if browsers are lenient. – Amadan Nov 20 '13 at 00:54
  • And what form does the `src` take? – David Thomas Nov 20 '13 at 00:54
  • 1
    *Well*, technically...if you refuse to follow the rules of HTML (or if you don't have control over the markup), you can do `$('[id="image-1"]').attr("src", "...")` to change multiple elements with the same id attribute. That's a workaround, but ideally your IDs should be unique. – nbrooks Nov 20 '13 at 01:10

3 Answers3

11

You need to use a class rather than an id. If you use class="imageClass" and reference the class in your jQuery it should work.

$(".imageClass").attr("src", "imagename");

The principle behind this is that an id should be unique whereas a class should be used for referencing multiple tags. You can have an id and a class on the same tag, but the id should be unique. For example, if you want all your headers to be green, you could do:

<h1 class="green-header">Text</h1>

But if you wanted to change one div in your site to center the text, you could do:

<div id="center-text">Text</div>
GBreen12
  • 1,832
  • 2
  • 20
  • 38
  • 2
    Probably useful to note that you can have the class as an addition to the id tags, not only as a replacement – ahansen Nov 20 '13 at 01:09
1

Try ^ attribute-starts-with-selector

$('img[id^="image-"]').prop("src", "imagename");


Read .prop() vs .attr()
Community
  • 1
  • 1
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
0

Try this:

$("img[id*='image-']").attr({src:"..."});
TLama
  • 75,147
  • 17
  • 214
  • 392
Doas
  • 1