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

Material UI Table dynamically updates with Firestore real-time data

My current code aims to update a Material UI table in real-time with data from a Firestore database. I can fetch the data and store it in an array, but when I assign this array to the table data, nothing changes. I've heard that I should use states fo ...

Automatic execution of expressions in browserify upon initialization

Utilizing browserify alongside node.js allows me to utilize require() in my JavaScript files. Within my game.js file, I have the following code: var game = new Phaser.Game(800, 600, Phaser.AUTO, 'snakeGame'); var menuState = require('./me ...

Tips for adjusting the vertical position of an image within a bootstrap column by a small amount

Apologies in advance if this question has already been addressed, and I am struggling to adapt it to my specific scenario. My objective is to adjust the positioning of the two images shown in the screenshot example below so that they align with the grey b ...

It is impossible to alter the data contained within the input box

Objective: Upon clicking a button to display the modal, the selected data (first and last name) should be inserted into an input box and editable. The user should be able to modify the data. Issue: The data entered into the input box cannot be edited ...

Angular2 Error: Cannot have two identifiers with the same name, 'PropertyKey' is duplicated

I am currently developing an application with angular2 using angular-cli. Unfortunately, angular-in-memory-web-api was not included by default. After some research, I manually added the line "angular-in-memory-web-api": "~0.1.5" to my ...

What is the best way to hand off slots to a descendant component in Vue 3?

Is it possible to have a component within a 'layout' component populate its slots? JS Fiddle <div id="app"> <layout> <page></page> </layout> </div> const app = Vue.createApp({}); ap ...

The error message states: "It is not possible to destructure the property 'createComponentInstance' of 'Vue.ssrUtils' as it is undefined for nuxt and jest."

I have been working on integrating the jest testing framework into my nuxt project, but I am facing a major obstacle. I am struggling to test a simple component and haven't been able to find a solution yet. If anyone has encountered the same issue, co ...

What is the best way to position the left sidebar on top of the other components and shift them to the

Currently, I am working on a project to display NBA data fetched from an API. I am aiming to recreate the design showcased here: Dribbble Design My main challenge lies in overlaying the left sidebar onto the main box and shifting the components sligh ...

ApolloError: Undefined fragment detected and unable to be used

Within the complex structure of my application, I encounter the following: import { gql } from '@apollo/client'; gql` fragment StuffTable on Stuff { id status } `; export const GetStuffDocument = gql` query GetStuff($id: ID!) { ...

Effective strategies for organizing component features in React

As I was reading through the React documentation, I came across the idea that using React effectively involves following the Single Responsibility Principle, meaning each component should have a specific purpose. I've already created a basic Gameboard ...

Add video details to the database using the API

I currently have my own database of YouTube videos which includes the video IDs found in the video links. My goal is to find a way to insert both the title and description of these videos into the database using the YouTube API and MySQL. Although I have ...

Warning: An unhandled promise rejection occurred while using agenda

I encountered an UnhandledPromiseRejectionWarning while running my project which utilizes the agenda package. Here is the code snippet: agenda.define('transferDBField', (job, done) => { if (this.tPrice) { this.prices.push(this.tP ...

What is the purpose of the 'onClassExtended' function in Extjs 6 for class definition?

Ext.define('Algorithm.data.Simulated', { needs: [ //.... ], onClassExtended: function(obj, info) { // .... } }) I came across this code snippet but couldn't locate any official documentation for it on Sencha ...

The issue here is that "onreadystatechange" in JS Ajax is not defined, even

For the past day, I've been struggling with this issue and going in circles. Any help would be much appreciated :-) Synopsis I'm facing a challenge with asynchronous AJAX calls to CGI using resolver and FQDN variables to obtain DNS resolution ...

Effective ways to manage extensive forms in Angular 2

I have a complex form in my application. What is the most effective way to collect data from this form and transmit it to the API using Angular 5? ...

Arrangement of Bootstrap card components

Each card contains dynamic content fetched from the backend. <div *ngFor="let cardData of dataArray"> <div class="card-header"> <div [innerHtml]="cardData.headerContent"></div> </div> <d ...

unable to modify the content within a div by clicking on a link

Lately, I've been experimenting with a code snippet I found on this fiddle: http://jsfiddle.net/unbornink/LUKGt/. The goal is to change the content of a div when clicking on links to see if it will work on my website. However, no matter which link I c ...

Ensure that the alert for an Ajax JSON record count remains active when the count is

Trying out Ajax JSON for the first time has been a bit tricky. Even though I hard coded "Record: 1" on the server side, it keeps alerting me with a total record of 0. I'm not sure where I went wrong. Could it be an issue with how I passed the array da ...

Testing components in React Native using asynchronous Jest methods

I have a component that triggers a fetch request when it mounts and then displays the results. I've been struggling to create a test snapshot of this component after the request is completed. I've searched on various forums like SO but haven&apo ...

Entering a new row and sending information through ajax

I'm looking for some help with a web page I have that includes a particular table structure: **Check out my Table*:* <table id="staff" class="table"> <thead> <tr> <th>First Name</th> <th>Last Nam ...