Nico V Nico V - 1 year ago 74
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 id="product-2" class="product">
<img id="product-img-2" class="product-images selected">

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

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 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 Source

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(){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download