Swapping images in Django(Using javascript/js)

This is the block of HTML code which contains one Main image and other additional images. If the user clicks on any additional images, the image should get replaced by the Main image. The logic works fine until I click the same image twice. After that the main image is lost

<img id="mainThumbnail" class="card-img-top mb-5 mb-md-0 rounded" src="{{ product.image.url }}" alt="{{ product.name }}" />

<!-- Additional Images -->
{% if additional_images %}
<div class="additional-images mt-4">
    <div class="row">
    {% for image in additional_images %}
        <div class="col-2">
            <img class="img-fluid rounded cursor-pointer thumbnail-image" src="{{ image.image.url }}" alt="Additional image for {{ product.name }}" onclick="swapImages('{{ image.image.url }}', this)" />
        </div>
    {% endfor %}
    </div>
</div>
{% endif %}

This is my javascript function

function swapImages(newImageUrl, clickedElement) {
    console.log(this);
    // Get the current main image URL
    const currentThumbnailUrl = document.getElementById('mainThumbnail').src;

    // Update the main thumbnail image with the new image URL
    document.getElementById('mainThumbnail').src = newImageUrl;

    // Update the clicked image with the previous main thumbnail image URL
    clickedElement.src = currentThumbnailUrl;

    // Remove 'selected' class from all thumbnail images
    document.querySelectorAll('.thumbnail-image').forEach(img => img.classList.remove('selected'));

    // Add 'selected' class to the clicked thumbnail image
    clickedElement.classList.add('selected');
}

document.querySelectorAll('.cursor-pointer').forEach(el => el.style.cursor = 'pointer');

I don’t wanted to use the javascript but that’s the only solution I can find. I’d want the image to replace when clicked.