I am seeking a way to conceal list elements according to a specified string input using JavaScript

Looking at the list items inside this div:

<div class="container">
    <h2>Vanishing Act Game</h2>
    <div>

        <li class="list-group-item go" id="item">Door#1</li>
        <li class="list-group-item go" id="item">Door#2</li>
        <li class="list-group-item go" id="item">Door#3</li>
        <li class="list-group-item go" id="item">Door#4</li>
        <li class="list-group-item go" id="item">Door#5</li>

    </div>

The idea is to have them disappear when "None" is typed into them. The JavaScript snippet for this is as follows:

     <script type="text/javascript">

        var TextInsideLi0 = document.querySelectorAll('li')[0].innerHTML; // Get text from line 1

        var TextInsideLi1 = document.querySelectorAll('li')[1].innerHTML; // Get text from line 2

        var TextInsideLi2 = document.querySelectorAll('li')[2].innerHTML; // Get text from line 3

        var TextInsideLi3 = document.querySelectorAll('li')[3].innerHTML; // Get text from line 4

        var TextInsideLi4 = document.querySelectorAll('li')[4].innerHTML; // Get text from line 5


        var MenuItems = document.querySelectorAll('.go'); // Gets menu items with class 'go'


        // Apply CSS to hide list item when "None" string is entered:

        if (TextInsideLi0 == "None") {
                MenuItems[0].classList.add('hidden')            
            } else if (TextInsideLi1 == "None") {
                MenuItems[1].classList.add('hidden')
            } else if (TextInsideLi2 == "None") {
                MenuItems[2].classList.add('hidden')
            } else if (TextInsideLi3 == "None") {
                MenuItems[3].classList.add('hidden')
            } else if (TextInsideLi4 == "None") {
                MenuItems[4].classList.add('hidden')
            }

    </script>

This code currently works for 5 list items. I am seeking advice on implementing a for loop that can handle an unlimited number of list items while maintaining the same functionality.

Answer №1

Avoid assigning the same id to each item you create.


        <li class="list-group-item go" id="item1">Door#1</li>
        <li class="list-group-item go" id="item2">Door#2</li>
        <li class="list-group-item go" id="item3">Door#3</li>
        <li class="list-group-item go" id="item4">Door#4</li>
        <li class="list-group-item go" id="item5">Door#5</li>

Control all elements using a loop, adjusting their innerHTML and applying classes accordingly.


   const allElements = document.querySelectorAll(".list-group-item");

     allElements.forEach(element => {
        if(element.innerHTML == "None") {
          element.classList.add("hidden");
        }
     });

Answer №2

It has been pointed out by CanUver that it is against the rules to assign the same ID to multiple HTML elements. Additionally, in your specific case, there is no requirement for individual IDs for each menu entry. As you have previously mentioned, once you have retrieved your menu element, you can simply iterate through its child elements, examine their inner HTML content, and apply the appropriate CSS class accordingly.

Answer №4

Hello there!

Below is a code snippet that can help you achieve what you asked for:

document
  // get all elements with class name 'li.go'
  .querySelectorAll("li.go")
  // hide the element if its inner text matches 'None'
  .forEach((item) => (item.innerText === "None" ? (item.hidden = true) : null));

Here are the resources I used:

Goodbye!

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

What is causing the issue with transmitting the server datetime to my local jQuery script?

I am facing an issue with my timeoftheserver.php page setup. The PHP code is quite simple: <?php echo date('D, d M y H:i:s'); ?> Similarly, the script on my local machine is also straightforward: var today; try { today = new Date($. ...

Encountering a Next.js Strapi error. TypeError: Fetch request unsuccessful

An error occurred during module build: UnhandledSchemeError: The plugin does not support reading from "node:assert" URIs (Unhandled scheme). Webpack natively supports "data:" and "file:" URIs. You might require an extra plugin to handle "node:" URIs. ...

Using the 'useMediaQuery' function from Material UI in a class component

Currently experimenting with Material UI's useMediaQuery feature to adjust the styles of a specific component, in this case the Button component. The objective is to eliminate the outline surrounding the button when the screen size decreases. The atte ...

Using a timer to make Ajax calls twice on a single webpage

Can multiple ajax calls be made simultaneously on the same page to different receiving div tags? I am struggling to find a solution to this issue. I have a total of 3 pages: a home page, and two PHP pages named status and alert which echo the results. Wi ...

Rails 4 application encountering issues with rendering views when making a $.ajax request

I am a beginner in Rails and I am in the process of sending model data to a controller method from JavaScript for rendering a list of results... function submitResults() { resultURL = "/result"; resultData = JSON.stringify(results); $.ajax({ typ ...

Generate slanted projection mapboxgl

Trying to develop a building simulator based on zoning codes. I can measure values, create floors, but struggling to extrude diagonally or create a perpendicular plane to the floor for evaluating angles from the street to limit building height (see image 2 ...

Setting a default value for Datetime in Django migrations

I have encountered similar questions about this issue on various platforms, but none of them have provided the accurate solution for my specific case: My challenge involves adding a 'created_time' field to existing models without a date column i ...

Enhance your website's performance by optimizing Javascript page loading time when using

I've implemented a simple JavaScript function that calculates the loading time of a URL: var beforeLoad = (new Date()).getTime(); $('#myiframe').one('load', function() { var afterLoad = (new Date()).getTime(); var result = ...

How can I dynamically insert a new HTML element into $event.target using Angular 2?

I have a webpage with a list of items. I want to display a "copy" button next to each item when the mouse hovers over it. I am currently able to create the "copy" button within the element using the following method: mouseOver(event) { if (event.tar ...

Is there a way to deliver information to a specific element on a client's HTML page?

My current project involves using Node.js to serve a webpage that collects user inputs and stores them in a mongodb server. The web page also displays these user inputs. I am trying to determine the best way to pass the user inputs from node.js to the < ...

Changing the background color with a switch function in ReactJS

After clicking a link, a view is rendered based on the "id" from a JSON. To enhance the user experience, I want to add a background color when a particular view renders and also toggle the style. This code snippet illustrates how the crawl is displaye ...

Is there a way to enable my progressBar to be draggable so that when clicked, it adjusts to a new currentTime position

I am trying to create a seekable audio progress bar in React, but I am facing issues with the seek function not working as intended. Below is my main play buttons file where all the code related to the progress bar is located. import React, { Component } ...

Refresh the homepage of a website using React Router by clicking on the site's logo from within the Home component

In most cases, when you click on a website's logo while on the homepage, it typically reloads the page. However, with React, clicking on the logo while already on the Home component does not trigger a reload. Is there a way to work around this issue? ...

What is the best way to attach a CSS class using an onclick function?

I need to dynamically apply a CSS class to a specific div when clicked using JavaScript. Here is the HTML structure: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv=&qu ...

Determine if a mobile application has been installed using Vue.js

I am currently developing a web application and have implemented a check to determine whether the user is accessing it from a mobile device or laptop. Let's consider the link as: my-site.com In addition to the web version, my site also offers a mobi ...

The @Input decorator in Angular 2/4 is designed to only transfer fundamental values and not collections or complex data

I have encountered an issue while attempting to use @Input with a list of objects, where the @Input variable ends up being undefined. What is functioning properly can be seen in home.component.html: <p> <it-easy [mycount]="countItem" (result ...

"Troubleshooting the lack of functionality in nested ajax calls, click events, or event

Initially, a navigation click event was created: $('#inner-navigation li a') .on('click', function (e) { e.preventDefault(); AjaxNavUrl.checkURL(this.hash); }); This event triggers an ajax call and respo ...

Update all Vue component imports to include the .vue extension at the end

The Vue CLI has decided to no longer support extensionless imports, causing compatibility issues with certain VS Code extensions like Vetur. In order to address this issue, I require all default component imports from a .vue file to include the file exten ...

Fill the table with information from a JSON file by selecting options from drop-down menus

I am currently working on a web application project that involves bus timetables. My goal is to display the timetable data in a table using dropdown menus populated with JSON information. While I believe I have tackled the JSON aspect correctly, I am facin ...

The imported JS file shows a warning that the variable 'myProperty' is defined but not utilized anywhere

When I try to import a variable from the same folder, why am I getting an error message saying it is defined but not used? I am sure that I am using it. Your input would be greatly appreciated! error 'componentName' is defined but never used. ...