How to change Image src for Multiple Images

css, html, javascript, jquery

Solution

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>

Problem

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.

Original source

Related problems