I’m writing a website and I have several identical product cards on the page. The card has a photo of the favorite icon. I need the src of the image to change when I hover over it. The src of the exact image that was pointed at changed. What complicates the situation is that all my cards have the same classes, and I cannot choose a specific one.
<div class="main-card">
<div class="main-card-img-holder">
<a href="#">
<img src="img/images/aj4PSG.png" alt="" class="main-card-img">
</a>
</div>
<a href="#" class="main-card-name"><p><b>Nike AirJordan 4 Retro PSG</b></p></a>
<div class="main-price-holder">
<p class="main-card-true-price">4 </p>
<p class="main-card-false-price">8</p>
</div>
<div class="main-add-to-cart-div">
<a href="#" class="main-add-to-cart-fav"><img src="img/icons/favorite.png" alt="" class="FavIcon"></a>
<a href="#" class="main-add-to-cart-link"><b>add to cart</b></a>
</div>
</div>
i was trying GetElementById, but it returns only first element, not all. I also tried querySelectorAll
3
Answers
Why aren’t you adding id to your cards? That way, you can write your JavaScript code to identify which element is selected and then you can obtain attributes of the selected element using getElementById(‘id’).
Here in your code, I’m presuming this is the div you want to be selected:
You can id to class to identify it uniquely and then obtain img’s src.
Now, you can select class and then subsequently child element with id.
If you are using jquery, it would become easier for selecting/identifying elements.
Using delegated event listeners bound to a suitable parent you can use the
event
itself to identify elements by inspecting theevent.target
&/orevent.currentTarget
– from there you can use standard DOM navigation techniques (parent,child,sibling selectors) and fashion your image change logic accordingly.You did not make clear what the image sources are to change to – as you referenced the
favourite icon
I understood that to mean swap the main img src for the favourite icon src – most likely a false assumption but this might helpYou can realize the hover script without having any
id
attributes. Use theev.target
of the hover event instead in order to identify the element concerned:Like Professor Abronsius I am also using delegated event handling. I add the events.to the
body
element and filter out only those elements having the class "main-card-img".