I'm trying to use getElementById
in external .js file to change img src
so it's easier to change my images from one file instead of having to go through hundreds of files I'm linking images from different dropshipping websites if there is an easier way of doing this I would be grateful if someone could help me thanks it also doesn't work the way I'd like here is my code:
JavaScript:
document.getElementById("item4").src = "item2.jpg"
document.getElementById("item5").src = "item62.jpg"
document.getElementById("item6").src = "item4.jpg"
document.getElementById("item7").src = "item5.jpg";
document.getElementById("item8").src = "item6.jpg";
document.getElementById("item9").src = "item3.jpg";
document.getElementById("item10").src = "item43.jpg";
document.getElementById("item11").src = "item43.jpg";
document.getElementById("item12").src = "item43.jpg";
document.getElementById("item13").src = "item43.jpg";
HTML:
<img class="images" id="item2" src="" alt="dress"/>
If you really need to get each of those items and remap their .src properties, I might just write a loop.
Then loop over the array and tie up your mappings:
If you just want to map an id value to a filename, you can make a map of the two:
And, then make a loop that goes through them the map data structure and assigns them all:
In general, putting more of this in a data structure and less in code is simpler and easier to maintain and debug.
If you have all these image tags in your HTML, you could also put the filename on a custom attribute for each image tag.
Then, you could just switch all items like this:
This function would automatically operate on any image with the right class name and the appropriate custom attribute and ignore any images without those properties.
The advantage of this type of code is that the HTML is the only data structure you need. Just add a new image, give it the right class and the right custom property and it's automatically included in the
switchImages()
algorithm.