sharataka sharataka - 2 months ago 7x
HTML Question

How to display and hide specific divs using javascript?

I have multiple images on a page. Each image has an id associated with it. For each image, I want the user to be able to click on a heart. When the user clicks on a heart, the open heart icon should be replaced by the closed heart icon for just that image. Similarly, when a user unhearts an image, the closed heart icon should get replaced by the open heart icon.

I'm having trouble implementing this in javascript correctly. How would I reference just the icon that needs to be changed? Any advice on how to implement this?


<script >
function wantToGo(id) {

function dontWantToGo(id) {


<div class='col-md-4'>
<img src = " ">
<!-- Open heart icon -->
<a href = "#" onClick = "wantToGo(4)"><i class="fa fa-heart-o"></i></a>
<!-- Closed heart icon -->
<a href = "#" onClick = "dontWantToGo(4)"><i class="fa fa-heart" aria-hidden="true" style = "color:red;"></i></a>

<div class='col-md-4'>
<img src = " ">
<a href = "#" onClick = "wantToGo(5)"><i class="fa fa-heart-o"></i></a>
<a href = "#" onClick = "dontWantToGo(5)"><i class="fa fa-heart" aria-hidden="true" style = "color:red;"></i></a>


You don't need to have 2 separated divs. You can just change the class in order to "switch" the icon (FontAwesome allows you to do that).

function switchHeart(el){
	var icon = el.querySelector('.fa');//Get the i element from his parent
	var opened = 'fa-heart-o';
	var closed = 'fa-heart';

<link href="//" rel="stylesheet"/>
<a href="#" onclick="switchHeart(this)"><i class="fa fa-heart-o" style="color:red"></i></a>

  • this in the onclick event listener allows you to reference the element triggering the click event.
  • In the function, we get the i child element from the parent that triggered the event.
  • A pair of variables with the classes for opened/closed heart.
  • We toggle each class, so if the opened class is present, we remove it. The same with the closed class.