What could be causing my issue with the if-else condition not functioning properly?

Why does the code only work for adding and removing styles in Part (else), but not returning the class when clicked again?

var navDropDown = document.querySelectorAll('.menu-item-has-children > a');
for (let i = 0; i < navDropDown.length; i++) {
  navDropDown[i].addEventListener('click', (e) => {
    if (navDropDown[i].nextElementSibling.style.display = 'none') {
      this.nextElementSibling.style.display = 'block;
    } else {
      this.nextElementSibling.style.display = 'none';
    }
  })
}

Answer №1

Can you spot the mistake in this line of code?

if (navDropDown[i].nextElementSibling.style.display = 'none') {

The error lies in the use of a single = instead of ==. In JavaScript, the single equals sign is meant for assignment, not comparison. As a result, the condition will always evaluate to true because it simply assigns the value 'none' to the style property. This means that the else block will never be triggered.

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

The express-fileupload throws an error saying "ENOENT: unable to locate the file or directory at 'public/images/name.ext'"

I am encountering an error ENOENT: no such file or directory, open 'public/images/name.ext from express-fileupload. I have searched for solutions to this issue, but none of the ones I found seem to work for me. Here are two examples: No such file or d ...

Is it possible for PHP to return jQuery code and have it execute immediately upon being echoed?

As someone who is new to jQuery and PHP, I have been tasked by my boss to create a login system for a web page that contains sensitive company information. The challenge is that this webpage consists of just one html/php file. Here is what I have done so ...

Is your Angular 2 routing failing to work properly after a page refresh or reload when using gulp?

I've recently started learning Angular 2, and I encountered an issue with routing. During the development phase, I ran my application using npm start. However, after migrating to gulp.js, when I run the application by typing gulp, everything works fin ...

Utilize jQuery's animate method to scroll to the top after toggling a class in Vue

I am in the process of developing a FAQ page using vue.js Here is what I have implemented so far: <li v-for="i in items | searchFor searchString" v-on:click="toggleCollapse(i)" :class="{ collapsed: i.collapse, expanded: !i.collapse }" > <p> ...

What is the process for dynamically setting @click in vue.js?

My array contains objects with methods as actions from a vue object. How can I dynamically set the @click event in a v-for loop? I attempted to use this.m1, "this.m1", "m1", but encountered an error: fns.apply is not a function. Javascript: new Vue ...

The implementation of SetInterval within nested functions in JavaScript appears to be malfunctioning

I am a beginner in the world of JavaScript and I am currently attempting to incorporate the setInterval method within functions in Js. JavaScript Code: var tar = document.getElementById("sample"); function dataSample(tar) { //setInterval ...

Initiating an AJAX call with custom headers

According to David Flanagan's book "JavaScript: The Definitive Guide, 5th Edition", it is recommended to send request headers before making an AJAX request. Is it necessary to do this for compatibility across different browsers? request.setRequestHe ...

Issue with login process: Selenium not recognizing my 'else' statement

Within my for loop, I have an if else statement that is used to verify data from an excel file in order to log in. However, when testing for bugs, it seems to be skipping the else statement. An error message is being displayed: no such element " email". ...

loading JSON file using dynamic JavaScript techniques

My Raspberry Pi is running a C++ application in the background that performs complex mathematical calculations based on sensor input and generates results every second. I want to showcase this data on a website by having the application create a JSON file ...

Shuffle math calculations involving subtraction by a percentage using node.js or JavaScript

Hello there! If you want to subtract, say 35%, from a number, you can use methods like this: var valueInString = "2383"; var num = parseFloat(valueInString); var val = num - (num * .35); console.log(val); But have you ever wondered how you could randomiz ...

Utilizing HTML and JavaScript to add grayscale effect to images within a table, with the ability to revert to the colored version upon mouseover

Seeking advice on utilizing the mouseover / mouseout event in javascript to implement grayscale on a table. The challenge requires creating a gray image grid (table) using HTML and then incorporating Javascript so that hovering over an image triggers it to ...

passing JSON data using JavaScript or jQuery

I have a JSON snippet that I need to parse using JavaScript or jQuery and convert into variables: name and meetup. Can you help me with this? Below is the JSON code: { "MYID": 1, "module": [ { "name": "Manchester", ...

Has Chrome's console disappeared?

After reinstalling Chrome and opening the dev tools with F12, I encountered an error with the following code: console.debug('test'); The error message displayed was Uncaught ReferenceError: console is not defined(…) This issue persisted acro ...

Exploring NextJS with Typescript to utilize the getStaticProps method

I'm currently enrolled in a NextJS course and I am interested in using Typescript. While browsing through a GitHub discussion forum, I came across an issue that I don't quite understand. The first function provided below seems to be throwing an e ...

Retrieve Data from HTML Table using jQuery

I am working with an HTML table that has the following values: <tr class="tuker1"> <td class="tuker-lft1"> Username </td> <td class="tuker-rght1" onclick="awardRoute()"> <a href="#"> AWARD ROUTE </ ...

What is the best way to extract individual words from a string based on a specified list of tokens?

I am currently working with a list of tokens used to create artificial Japanese words, which is represented by the following array: var syllables = ["chi","tsu","shi","ka","ki","ku","ke","ko","ta","te","to","sa","su","se","so","na","ni","nu","ne","no","ha ...

Finding the arithmetic operator and then assigning both the operator and its index to a globally accessible variable can be accomplished through a

Hello, I am currently learning web development and as a beginner project, I am working on creating a calculator in React. My goal is to have the selected arithmetic operation ("+", "/", "-", or "X") executed when the user clicks "=". To achieve this, I s ...

What is the method for retrieving information from a JSON file that has been uploaded?

I am working with some HTML code that looks like this: <input type="file" id="up" /> <input type="submit" id="btn" /> Additionally, I have a JSON file structured as follows: { "name": "Jo ...

Regular Expression: locate the occurrence of "//" followed by any character other than a space

I am looking to add a space by replacing the target with the code "// ". That's all you need to know from the title. My attempts so far have looked like this: \/\/\b(?! ) However, this approach does not catch strings like "//$..." ...

Stopping videos in the JQuery Cycle Plugin triggers the stop event

Currently, I have a simple cycle set up with YouTube videos using the following code: <script type="text/javascript"> $(document).ready(function () { $('#cycle').cycle({ fx: 'fade', sp ...