JavaScript's ability to show and hide div elements functions properly in Internet Explorer, but is encountering issues in Firefox and Chrome

I have a total of 20 spans with unique IDs, all set to hidden in my stylesheet.

To toggle the visibility of these spans upon clicking on sections of an image map, I created this script:

function showDiv(pass) {
    var divs = document.getElementsByTagName('span');    
    for (i = 0; i < divs.length; i++) {
        if (divs[i].id.match(pass)) {
            (pass).style.visibility = 'visible';
            divs[i].style.visibility = 'hidden';
        }          
    }
} 

     

The script works flawlessly in Internet Explorer, but Firefox seems to be having issues. Chrome also shows some minor problems that I believe can be fixed.

If you have any insights into why Firefox is not working or any suggestions for improvement, they would be sincerely appreciated and rewarded generously in the afterlife :)

Answer №2

The reason for the issue is that you are passing a string and then later using it as an element reference. Internet Explorer needs to search the Document Object Model (DOM) to locate an element with an ID that matches the string.

Here is a suggestion...

if (divs[i].id.match(pass)) {
    document.getElementById(pass).style.visibility = 'visible';
    divs[i].style.visibility = 'hidden';
}

Alternatively, it is possible that the String.match function expects a regular expression. If the earlier solution does not solve your problem, you can try this...

if (divs[i].id.match(new RegExp(pass, 'gi'))) {

Answer №3

key is a unique identifier. When working with Firefox, IDs of elements in the Document Object Model (DOM) cannot be accessed as global variables. Trying to set id.style.visibility = 'visible'; will not work in this situation. Instead, your function needs to be structured like the following:

function displayElement(key) {
    var elements = document.getElementsByTagName('div');    
    for (i = 0; i < elements.length; i++) {
        if (elements[i].id.match(key)) {
            elements[i].style.visibility = 'hidden';
        }          
    }
    document.getElementById(key).style.visibility = 'visible';
}

You can adjust the visibility of key outside of the loop because it only needs to be done once.

Answer №4

    if (divs[i].id.match(password)) {

Why is password being used as a regular expression here? It's not typical to see match with this setup.

        (password).style.visibility = 'visible';

Whether password is a string or a regex, it doesn't make logical sense in this context. Both types do not have a style property. Placing the variable in parentheses does not change anything. I've tested this code across different browsers and it doesn't work properly, including IE.

Perhaps you intended something like this instead:

function displayDiv(password) {
    var divs= document.getElementsByTagName('span');    
    for (var i= 0; i<divs.length; i++)
        divs[i].style.visibility= divs[i].id==password ? 'visible' : 'hidden';
}

Also, notice the use of var i: this declaration prevents i from becoming a global variable. Not defining it can lead to unexpected errors when multiple for i loops start conflicting with each other.

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

Switching between height: 0 and height:auto dynamically with the power of JavaScript and VueJS

Currently, I am changing the height of a container from 0px to auto. Since I do not know the exact final height needed for the container, using max-height could be an option but I prefer this method. The transition from 0 to auto works smoothly, however, ...

Tips on adding several elements to an array depending on the selected value from various checkboxes?

I am working on a project where I need to populate an array based on selected checkboxes. Let's assume we have 3 arrays containing strings: const fruits = ["Apple", "Banana", "Orange", "Grapes"]; const vegetable ...

Unlocking the potential of input values in Angular.jsDiscovering the secret to

I'm currently experimenting with the angular date picker directive. My goal is to retrieve the entered date value from the date picker and log it to the console. However, all of my attempts so far have been unsuccessful. Here's a snippet of my c ...

Encountering the error "ReferenceError: Cannot access 'data' before initialization" during deployment on Vercel

I encountered a problem with my project after trying to implement dynamic routing. Initially, everything was working fine locally and during deployment. However, when I attempted to incorporate dynamic routing, errors started to occur. Unfortunately, I am ...

The functionality of the Javascript window.print() method is limited to a single use

I've been working on an Angular project and I have the following code snippet implemented in one of the components. Everything works fine when I try to print for the first time using the onClickPrint() method, but it doesn't seem to trigger when ...

Tips for converting a URL to the correct route in emberjs when the location type is set to history

After creating a basic Ember.js application and setting the router location type to 'history', I encountered an issue with the generated URLs. Instead of the expected URL format like http://localhost/#/post/1, the Ember.js application was changi ...

Finding the amount of memory that can be used in a WebView

I'm currently developing an application that features a WebView running JavaScript code. This particular JavaScript code tends to be memory-intensive and can sometimes exceed the allotted memory, leading to crashes in the WebView's Chromium proce ...

What is the method for iterating through rows using csv-parser in a nodejs environment?

I'm working on a script to automate the generation of code for my job. Sometimes I receive a .csv file that contains instructions to create table fields, sometimes even up to 50 at once! (Using AL, a Business Central programming language.) Here is th ...

Node JS Client.query not returning expected results

Currently, I am developing a Web Application that interacts with my PostgreSQL database. However, when I navigate to the main page, it should display the first element from the 'actor' table, but unfortunately, nothing is being retrieved. Below i ...

Send the form via ajax

I am in the process of creating a unique application for my university, which is essentially a social network. One key feature I need to implement is the ability for users to add comments, which involves inserting a row into a specific database. To achieve ...

Is it possible to integrate Vue.js within a web component?

Is it possible to utilize VueJS to control behavior within a web component? In other words, if the VueJS library is included as a script reference, can it be integrated in the same way as on a standard HTML page, but within the confines of a web componen ...

Saving the author of a message from one function and transferring it to another

I'm currently working on a Discord bot that manages tickets as applications. I've almost completed it, but I want the bot to log the closed ticket when the -close command is used. I've experimented with different approaches, such as using a ...

Is there a way to use ng-click to switch the ng-src of one image with that of another?

*I made updates to the plunkr and code to reflect my localhost version more accurately. It turned out that the AngularJS version was not the issue even after fixing the previous plunkr.* Let me start by saying that I am facing some challenges with Angular ...

Selecting from a variety of options presented as an array of objects

I am currently working on a component that allows users to select roles: https://i.stack.imgur.com/bnb9Y.png export const MultipleSelectChip = ({ options, label, error, onRolesUpdate, }: Props) => { const theme = useTheme(); const [selected ...

Display various MongoDB datasets in a single Express route

I currently have a get method in my Express app that renders data from a MongoDB collection called "Members" on the URL "/agileApp". This is working fine, but I now also want to render another collection called "Tasks" on the same URL. Is it possible to ...

How can I simulate pressing the ENTER key in Selenium without selecting any element?

Having trouble using the firefox selenium plugin and sending the enter key after pasting text? The ENTER key press should not interact with any other element on the page, just a simple 'dumb' ENTER key press. error [error] Element name=code not ...

Improve numerous conditions

I am currently working on a project that involves Angular and Node. In this project, I have written a function with multiple if and else if statements containing various conditions. The code looks complex and lengthy, and I want to refactor it to make it ...

Having trouble getting the default NextJS template to work with TailwindCSS

Sysinfo: > Windows 11 > Node: v18.16.0 > Next: 13.4.13 > Tested Browser: Firefox, Chrome. Step to Reproduce To recreate the issue, I created a NextJS project using the command npx create-next-app tezz with specific options selected: Would you ...

Using AJAX to dynamically load content from a Wordpress website

Currently, I have been experimenting with an AJAX tutorial in an attempt to dynamically load my WordPress post content onto the homepage of my website without triggering a full page reload. However, for some reason, when clicking on the links, instead of ...

Krajee Bootstrap File Input, receiving AJAX success notification

I am currently utilizing the Krajee Bootstrap File Input plugin to facilitate an upload through an AJAX call. For more information on the AJAX section of the Krajee plugin, please visit: Krajee plugin AJAX The JavaScript and PHP (CodeIgniter) code snippe ...