Nico V Nico V - 20 days ago 9
HTML Question

Select sibling not working as expected

I've come across a somewhat silly problem.
Take a look at the following html:

<div id="product-container">
<div id="product-1" class="product">
<img id="product-img-1" class="product-images">
</div>

<div id="product-2" class="product">
<img id="product-img-2" class="product-images selected">
</div>

<div id="product-3" class="product">
<img id="product-img-3" class="product-images">
</div>
</div>


What I want to do is whenever the page loads it sets the first product's image class to 'selected' or whenever you click a product image, it changes the class of that image to 'selected' and removes this same class from the other ones.

I have tested this with the following

$("img.product-images").on('click', function(){
$(this).addClass('selected').siblings().removeClass('selected');
});


This works, but only when you click an image, this doesn't work when the page is loaded.

To fix this I wrote the following:

function updateActiveImg(product = firstProduct()){ // returns first available product (I've tested this and this works as desired)
// attempt 1, doesn't work: it does add the class to the correct image, but when I click another it just adds the class to that image whithout removing it from its siblings
$('#product-' + product).addClass('selected').siblings().removeClass('selected');
// attempt 2, doesn't work: this will remove the class from all the cildren, including the one I want selected
$('#product-' + product).addClass('selected').parent().find('.product-images').removeClass('selected');
// attempt 3, doesn't work: thought this was the final solution, but don't see why it wouldn't work
$('#product-' + product).addClass('selected').parent().find('.product-images').not('#product-' + product).removeClass('selected');
}


Does anyone know what I'm missing here?

Answer

You need to get its parent sibling and then the element. To make it work initially, trigger click event for the first element.

$("img.product-images").on('click', function(){
    $(this).addClass('selected').parent().siblings().find('.product-images').removeClass('selected');
}).eq(0).click();
Comments