What could be the reason why my JavaScript code for adding a class to hide an image is not functioning properly?

My HTML code looks like this:

<div class="container-fluid instructions">
    <img src="chick2.png">
    <img class="img1" src="dice6.png">
    <img class="img2" src="dice6.png">
    <img class="img3 threeChoices" src="dice6.png">
    <img class="img4 fourChoices" src="dice6.png">
    <img src="chick1.png">
  </div>
<div class="dropdown">
      <button class="btn btn-info dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
        2
        <span class="caret"></span>
      </button>
      <ul id="list" class="dropdown-menu dropdown-info" aria-labelledby="dropdownMenu1">
        <li><a href="#">2</a></li>
        <li><a href="#">3</a></li>
        <li><a href="#">4</a></li>
      </ul>
      <input type="text" name="" value="" placeholder="Choice 1"> <br>
    </div>

Here is the JavaScript portion:

let links = document.querySelectorAll('#list li')
links.forEach((el) => {
  el.addEventListener('click', (event) => {
    let numberOfChoices = event.target.innerText
    document.getElementById('dropdownMenu1').innerHTML = `${numberOfChoices}<span class="caret"></span>`
    console.log(numberOfChoices)

    // Showing Correct Number of Boxes
    if (numberOfChoices === 2) {
      document.querySelectorAll(".img3").classList.add(".invisible");
    }
  })
})

Your CSS should include this:

.invisible{display: none;}

If you select '2' on the dropdown, the image with class img3 should disappear. If it's not working as expected, any help would be appreciated. Thank you in advance.

Answer №1

After reviewing your code, I identified three issues that were causing the image to not be hidden when the class was added.

The first issue was comparing a string with an int, so you need to make the necessary changes there.

Secondly, using querySelectorAll(".img3") prevented accessing the classList property before applying a forEach() loop on the result. It should be changed to querySelector(".img3").

Lastly, adding the .invisible class resulted in a syntax error like <div class=".invisible">, instead, simply add the class name invisible.

Below is the corrected code:

let links = document.querySelectorAll('#list li')
links.forEach((el) => {
  el.addEventListener('click', (event) => {
    let numberOfChoices = event.target.innerText
    document.getElementById('dropdownMenu1').innerHTML = `${numberOfChoices}<span class="caret"></span>`
    console.log(numberOfChoices)

    // Showing Correct Number of Boxes
    if (numberOfChoices === "2") { // <------- fix 1
      var element = document.querySelector(".img3"); // <------ Fix 2
      element.classList.add("invisible"); // <------ Fix 3
    }
  })
})
.invisible {
  display: none;
}
<div class="container-fluid instructions">
  <img src="chick2.png">
  <img class="img1" src="dice6.png">
  <img class="img2" src="dice6.png">
  <img class="img3 threeChoices" src="dice6.png">
  <img class="img4 fourChoices" src="dice6.png">
  <img src="chick1.png">
</div>
<div class="dropdown">
  <button class="btn btn-info dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
        2
        <span class="caret"></span>
      </button>
  <ul id="list" class="dropdown-menu dropdown-info" aria-labelledby="dropdownMenu1">
    <li><a href="#">2</a></li>
    <li><a href="#">3</a></li>
    <li><a href="#">4</a></li>
  </ul>
  <input type="text" name="" value="" placeholder="Choice 1"> <br>
</div>

------------------- UPDATE FOR JQUERY ------------------------

If you want to use JQuery and streamline the code further, here are the required modifications. Firstly, include JQuery in your code either by linking the js file from the cloud or downloading it.

With JQuery in place, switch from using

document.querySelector('selector')
to $('selector') for selecting elements. JQuery treats single and multiple element selections uniformly, returning an array for multiple elements that can be manipulated directly without needing forEach or each. That's the next change.

As you already suggested in the comments, the final modification involves selecting various elements with different classes or ids using the , separator within the selector and then employing the addClass method.

$(document).on('click', '#list li', function(event) {
  let numberOfChoices = event.target.innerText
  $('#dropdownMenu1').html(numberOfChoices + "<span class='caret'></span>")
  console.log(numberOfChoices);

  // Showing Correct Number of Boxes
  if (numberOfChoices === "2") {
    $(".img3, .img4").addClass("invisible");
  }
})
.invisible {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- IMPORTANT here you add jquery from the cloud -->
<div class="container-fluid instructions">
  <img src="chick2.png">
  <img class="img1" src="dice6.png">
  <img class="img2" src="dice6.png">
  <img class="img3 threeChoices" src="dice6.png">
  <img class="img4 fourChoices" src="dice6.png">
  <img src="chick1.png">
</div>
<div class="dropdown">
  <button class="btn btn-info dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
        2
        <span class="caret"></span>
      </button>
  <ul id="list" class="dropdown-menu dropdown-info" aria-labelledby="dropdownMenu1">
    <li><a href="#">2</a></li>
    <li><a href="#">3</a></li>
    <li><a href="#">4</a></li>
  </ul>
  <input type="text" name="" value="" placeholder="Choice 1"> <br>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error Message: discord.js is unable to retrieve the specified property 'find' due to it being undefined, resulting in

While working on a command for my discord bot, I encountered an error. As I am new to programming, please forgive me if it's something simple that I couldn't figure out. TypeError: Cannot read property 'find' of undefined at Object. ...

Steps for refreshing a JavaScript function responsible for generating a table

Within the code snippet provided, there is a click event attached to a table row. Upon clicking a row, the script extracts the id value from the first column and triggers a REST call. Subsequently, a new table is constructed using a third-party function ca ...

Leveraging $this in conjunction with a jQuery plugin

I'm experimenting with a code snippet to reverse the even text in an unordered list: $(document).ready(function () { $.fn.reverseText = function () { var x = this.text(); var y = ""; for (var i = x.length - 1; i >= 0; ...

What is the best way to display a child component inside an iframe using Vue.js?

Looking to provide a live preview of an email before sending it out, I've opted to use an iframe to contain the preview and prevent style leaks. The goal is for the preview to update dynamically as the user fills out form details. How can I display a ...

Guide to defining font style in vanilla-extract/CSS

I'm trying to import a fontFace using vanilla-extract/css but I'm having trouble figuring out how to do it. The code provided in the documentation is as follows: import { fontFace, style } from '@vanilla-extract/css'; const myFont = fo ...

What is the best way to achieve a perfect rounded div using Bootstrap 4?

While browsing through the Bootstrap documentation and searching on stackoverflow, I came across a solution to create circular images using border-radius set at 50%. However, when I tried implementing it with my slightly oversized image, it ended up lookin ...

What strategies can be employed to mitigate the activation of the losing arm in a Promise.race?

My current task involves sending the same query to multiple identical endpoints (about five) across various Kubernetes clusters. The goal is to aggregate the results without any delays and report failures to the user while continuing with the process seaml ...

Utilize a vanilla JavaScript object as the primary model in Ember

Can a plain JS object, such as a literal object, be used as a model in EmberJS? I've noticed that all the examples in the documentation utilize Ember.Object or a datastore. I understand that I may not have access to features like observables with pl ...

mysterious supplier factoryprovider <- factory <- angular js controller

I'm encountering an issue with injecting dependencies from a service to a controller. Despite adding it, I keep receiving the following error: Unknown provider: websiteFactoryProvider <- websiteFactory <- listCtrl My main goal is to display ...

What is the reason behind the varying dimensions of images on Chrome compared to Firefox?

I've been working on enhancing my web development skills and decided to create a personal portfolio. During the development process, I focused mainly on Firefox as my browser of choice. One section of the portfolio includes showcasing my skills using ...

The Sequelize error message states: TypeError: an array or iterable object was expected, but instead [object Null] was received

I am encountering an issue with the findOne method from sequelize in my model. The error message I am getting states that the table referenced by the model is empty. How can I resolve this? Unhandled rejection TypeError: expecting an array or an iterable ...

Guidelines for sending an array from a Laravel Controller through AJAX and generating a button based on the received data

Before making a selection, I click on the Color button: <form class="form form-variant"> {{ csrf_field() }} <button type="submit" class="btn btn-success che ...

Creating an image selection feature using ejs and express: a step-by-step guide

As I develop a blog site with a unique post management system using node, express, moongoDB, and EJS, everything seems to be running smoothly. However, the challenge arises when attempting to integrate Cloudinary uploaded images from my mongoDB to allow fo ...

Sequencing requests and processing data in Node.js through event handling

Is there a way to combine the responses from two requests into one single JSON response? The goal is to have an array containing both {response1JSON} and {response2JSON}, with each response streaming data that needs to be read. function getSongs() { c ...

I wonder what the outcome would be if I used res.send to send a JSON file instead of res.json

Is it possible to send a JSON file using res.send in NodeJs instead of res.json? What are the potential consequences of doing this and why is it recommended to avoid this practice? ...

Transferring JavaScript files via Node server using NowJS

As someone new to Node, I need some help with a server-client web application I'm creating for a board game using Raphael for graphics. The issue I'm facing is that while the server successfully sends the HTML file in response to requests, the b ...

Is it possible to load Javascript using AJAX with jQuery?

So I have this JavaScript code that I insert into a webpage using the following: <script type="text/javascript" src="http://ext.nicovideo.jp/thumb_watch/sm13154955?w=640&h=395"></script> It basically places an object/embed code into the w ...

CSS hover image resizing not functioning as expected

Is there a way to dynamically scale up an image when hovered over? I'm trying to achieve an effect where the image increases from 100x75 pixels to 300x225 pixels. Everything seems to be working fine with the layout, but the width doesn't seem to ...

Creating a popup window using HTML

I am attempting to create a pop-up window using HTML, but I'm struggling to get it to appear in the desired way. My goal is this: to have a pop-up show up when the profile image is clicked on. Here's the HTML <span class="profile"><im ...

Tips for ensuring only one property is present in a Typescript interface

Consider the React component interface below: export interface MyInterface { name: string; isEasy?: boolean; isMedium?: boolean; isHard?: boolean; } This component must accept only one property from isEasy, isMedium, or isHard For example: <M ...