Unable to modify div style using a JS function

I am attempting to show different divs based on the button clicked, with all starting with a display style of "none" except for one default div called "atualizacoes". After clicking a button, all divs should be set to display="none", and then the specific div associated with that button should be set to display="block". However, I am facing an issue as when I click a button, the default div disappears but nothing else appears.

This is my approach:

The steps include:

snippet 1 - function used in index.html to change display styles

snippet 2 - CSS rule in stylesheet

snippet 3 - relevant parts of index.html code

<script type="text/javascript">
function replace(show) {
  document.getElementById('default').style.display="none";
  document.getElementById('ecra').style.display="none";
  document.getElementById(show).style.display = "block";
}
</script>
.ecra
{
    display: none;
}
<!DOCTYPE html>
<html lang="en>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">
        <title>University Platform</title>
        <!-- Bootstrap core CSS -->
        <link href="bootstrap/css/bootstrap.css" rel="stylesheet">
        <!-- Custom styles for this template -->
        <link href="dashboard.css" rel="stylesheet">
        <!-- jquery -->
        <script src="assets/js/jquery.min.js"></script>
        <script src="bootstrap/js/bootstrap.min.js"></script>
      
  </head>
<body>

<!-- Buttons on sidebar -->
<div class="row">
  <h3>Options</h3>
  
  <button type="button" class="btn btn-default botao pull-left" onclick="replace('addestudante')">Add Student</button>
</div>

<div class="row">
  <button type="button" class="btn btn-default botao pull-left" onclick="replace('adduc')">Add UC</button>
</div>

<!-- Divs to switch around -->
<div class="row" id='default'>
           <p>Hello World</p>                     
</div>

<div class="row ecra" id='addestudante'>
  <button type="button" class="btn btn-default">TEST 1</button>
</div>

<div class="row ecra" id='adduc'> 
  <button type="button" class="btn btn-default">TEST 2</button>
</div>
  
</body>

Why is this function not working as expected? Is there an error in my code?

Answer №1

Your code has a few issues that need to be addressed.

Firstly, you are trying to target elements with the ID "ecra", but there are no such elements in your document. Instead, you should target elements with the class "ecra" by using

document.getElementsByClassName("ecra")
.

Secondly, you made a typo when referencing the show element as style.

To fix these issues, consider using the following modified function:

function replace(show) {
    document.getElementById("default").style.display = "none";
    Array.from(document.getElementsByClassName("ecra")).map(element => element.style.display = "none");
    document.getElementById(show).style.display = "block";
}

Answer №2

In order to retrieve elements by their class name, you can target the ecra class using the querySelectorAll method and iterate through them using a loop. Instead of using getElementsByClassName, I prefer this method as it keeps the code shorter and returns a NodeList.

function toggleVisibility(display){
    var elements=document.querySelectorAll('.ecra');
    document.getElementById('default').style.display="none";
    for(var i=0; i<elements.length; i++){
        !function(i){
            elements[i].style.display="none";
        }(i)
    }
    document.querySelector('#'+display).style.display = "block";
}

Answer №3

Upon examining your webpage, I noticed that jQuery has been imported. Therefore, my recommendation is to utilize jQuery.

<script type="text/javascript">
        function replace(show) {
          jQuery(function($){
                $("#default").css({
                    "display" : "none"
                });
                $(".ecra").css({
                    "display" : "none"
                });
                $("#"+show).css({
                    "display" : "block"
                });
          });
        }
</script>

An update has been made to address missing characters.

Answer №4

JS corrected : http://jsfiddle.net/csfd8x35/

.ecra
{
    display: none;
}
<!-- sidebar buttons -->
<div class="row">
  <h3>Options</h3>
  <button type="button" class="btn btn-default botao pull-left" onclick="replace1('addestudante')">Adicionar Estudante</button>
</div>

<div class="row">
  <button type="button" class="btn btn-default botao pull-left" onclick="replace1('adduc')">Adicionar UC</button>
</div>

<!-- divs to switch around -->
<div class="row" id='default'>
           <p> Hello World </p>                     
</div>

<!-- CSS rule - all "ecra" divs start invisible-->
<div class="row ecra" id='addestudante'>
  <button type="button" class="btn btn-default">  TEST 1</button>
</div>

<div class="row ecra" id='adduc'> 
  <button type="button" class="btn btn-default"> TEST 2</button>
</div>

<script>
    function replace1(show) {
  document.getElementById('default').style.display="none";
  var allByClass = document.getElementsByClassName('ecra');
                for (var i=0;i< allByClass.length; i++) {
                      allByClass[i].style.display = "none";
                }
  document.getElementById(show).style.display = "block";
}
</script>
 

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

Creating a dropdown feature for menu items in Vue when the number or width of items exceeds the menu bar's limits

I am working on a navigation bar that displays menu items as tabs. One issue I am encountering is when the number of menu items exceeds the space available, I need to move the excess items into a dropdown menu (showmore) using Vue. Here is an example of t ...

What is the best way to extract the geometry information from a gltf object?

I've been using three.js to load a gltf file with the gltfloader, and now I'm trying to create a particle system. However, I'm having trouble getting the geometry object that I need. function initModel() { var planeGeometry = new THREE ...

confirmation box for deleting a row in a grid view

I am looking to enhance the delete confirmation box on my Gridview delete function. Currently, I am using a basic Internet Explorer box for confirmation but I want to display a more stylish confirmation box. Here is the JavaScript code snippet within my gr ...

Encountering a "403 Forbidden" error upon deployment to the server due to

Situation: I am developing a website using Spring web MVC, JSP, and HTML/JavaScript. One of the features I have implemented is a search function that communicates with imdbapi.org to retrieve movie/TV show information in JSON format via AJAX. The JSON resp ...

Challenges with Page Loading in Selenium

Inquiry: When a URL is accessed in a web browser, the page begins to load. A loading symbol appears at the top, and once it stops, our selenium script continues with the next steps. However, there are instances where the page takes longer to load all its ...

Using Selenium IDE to click on a checkbox within a table row

Currently, I am utilizing Selenium IDE to navigate through a table with multiple rows and columns. Each row within the table contains its own checkbox for selection purposes. In my attempt to search for a specific row, I have been using the following comm ...

The phrase 'nodemon' is not identified as a valid cmdlet, function, script file, or executable program

Recently I started working with Node.js, but I encountered an error when trying to run a program. The error message says "the term nodemon is not recognized the name of cmdlet, function, script file or operable function". Can someone please assist me with ...

Automate the process of saving information to Google Sheets using Google AppScript

I have a Sheet named 'Automatic' where I've imported a set of data using IMPORTXML. My goal is to update this data list daily at the same time to create a database with various stock quotes over time. Is there a way to accomplish this usin ...

Removing the year data and converting the month in JavaScript

Currently, I am utilizing the following code snippet to parse XML in Javascript: $this(find).text() When this code runs within an HTML environment, the output for the date from the XML data appears as: 2014-04-07T19:48:00 My objective is to format it l ...

Unable to retrieve /ID from querystring using Express and nodeJS

I am brand new to the world of Express and nodeJS. I have been experimenting with query strings and dynamic web pages, but I keep getting an error saying that it cannot retrieve the ID. I'm completely lost as to where I might have made a mistake. An ...

Updating the scope in Angular when changing the image source using ng-src is not working

A snippet inside my controller looks like this: $scope.onFileSelect = function($files) { for(var i = 0; i < $files.length; i++) { var file = $files[i]; $scope.upload = $upload.upload({ url: '/smart2/api/files/profi ...

Tips for transferring simple CSS formatting to an independent stylesheet

As part of a university project, I am working on a basic website. Initially, I used in-line styling for the website design. However, the subject coordinator has now changed the requirements and we are only allowed to use an external CSS stylesheet. Most of ...

Utilizing Vue to create multiple components and interact with Vuex state properties

I am currently learning Vue and using it with Vuex (without Webpack). However, I am facing some challenges while implementing a simple example and the documentation is not very clear to me. One issue I encountered is that I cannot access the Vuex st ...

The issue with the search box not being correctly displayed on Google CSE using Twitter Bootstrap

Having an issue with the Google Custom Search (CSE) as it is not displaying the search box and button correctly. I am using Twitter Bootstrap v3.1.0. <script> (function() { var cx = '009077552906670546181:2ufng0dmsos'; ...

Quickest method for sorting an array of objects based on the property of another object's array

Within my code, I have two arrays of objects, both containing a "columnId" property. My goal is to rearrange the first array to match the order of the second. I attempted the following method: filtered = visibleColumns.filter(function(v) { re ...

Simplified React conditional rendering made easy

Currently, I am utilizing React 16 with Material-Ui components. In my root component, I have a requirement to load a tab and a view conditionally based on a property. Although I have managed to implement this functionality, the code appears quite messy a ...

When using react-router-dom, a blank page may appear for routes that contain more than one path segment followed by a single forward slash "/"

Whenever I attempt to set up a route with more than one "/" (e.g. "/testing/test"), React simply displays a blank page instead of showing the Test component along with the navigation bar and footer. Interestingly, the route "/testi ...

Guide on incorporating `Animate.css` into an Angular application

I've been attempting to implement the bounceInUp animation from animate.css on a div upon showing it, but I can't seem to get it to work. What am I doing wrong? Can someone guide me on the correct way to achieve this effect? This is my CSS code ...

Issue with the System.Web.HttpRequestValidationException

I've been grappling with an issue related to a week-long problem that involves the error message System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client. This issue arises specifically when de ...

Guide to updating a database using ajax and javascript in asp.net mvc without the need to refresh the page

Is there a way to update the value of an enumdropdownlist from "active" to "inactive" in my database through an ajax call without having to refresh the page? I am unsure whether to use a javascript method or ajax.beginform for this task. I attempted to us ...