0

I want to use javascript to automatically update my index.html doc based on files which are inside the images directory.

Here's a snippet of how the html should look if the directory contained the following 3 image files 'moth_forsale.jpg', 'art_sold.jpg', 'bat_forsale.jpg'.

<a class='gallery-link' target="_blank" href='../images/moth_forsale.jpg'>
  <img src="../images_small/moth_forsale.jpg" class="all forsale">
</a>
<a class='gallery-link' target="_blank" href='../images/art_sold.jpg'>
  <img src="../images_small/art_sold.jpg" class="all forsale">
</a>
<a class='gallery-link' target="_blank" href='../images/bat_forsale.jpg'>
  <img src="../images_small/bat_forsale.jpg" class="all forsale">
</a>

As shown, in addition to updating the file paths, I also need to update the class, with either 'forsale' or 'sold', depending on what the image name contains.

Frankie
  • 79
  • 5

1 Answers1

0

try this:

document.querySelectorAll('.gallery-link > img').forEach(img => {
  img.classList.add(img.src.includes('forsale') ? 'forsale' : 'sold');
});

if you need to check and remove previous classes, you can use img.classList.remove() method.

If you only need to address the image in your CSS you can use partial attribute CSS selector:

.gallery-link > img[src*=forsale]

use it to get all images with forsale string intheir src attribute, and

.gallery-link > img[src*=sold]

for images with sold

Andriy
  • 14,781
  • 4
  • 46
  • 50