Loop through the elements of a class in JavaScript and choose all except for the one that was

Imagine having 5 div elements, each with a similar onclick-function that hides the other divs when clicked.

HTML:

<div id="1" class="divs" onclick="hide()"></div>
<div id="2" class="divs" onclick="hide()"></div>
<div id="3" class="divs" onclick="hide()"></div>
<div id="4" class="divs" onclick="hide()"></div>
<div id="5" class="divs" onclick="hide()"></div>

This is what has been attempted:

JavaScript:

function hide(){
    var divs = document.getElementsByClassName("divs");
    for(var i = 0; i < arrows.length; i++){
        if(this != arrows[i]){
            arrows[i].style.display = "none";
        }
    }
}

The current outcome results in all divs being hidden, rather than just leaving the clicked element visible. Looking to achieve this using vanilla JS instead of jQuery's ":not()" selector. Any tips?

Appreciate any help provided.

Answer №1

Avoid using event handler content attributes; instead, utilize event listeners for better functionality.

var divs = document.getElementsByClassName("divs");
function hide() {
  for(var i = 0; i < divs.length; i++){
    if(this != divs[i]){
      divs[i].style.display = "none";
    }
  }
}
[].forEach.call(divs, function(div) {
  div.addEventListener('click', hide);
});
<div id="1" class="divs">1</div>
<div id="2" class="divs">2</div>
<div id="3" class="divs">3</div>
<div id="4" class="divs">4</div>
<div id="5" class="divs">5</div>

Answer №2

To hide a specific div in HTML, you can pass this as a parameter inside the hide() function. Then, in your JavaScript function, you can manipulate the clicked DOM object to show the desired div.

Sample HTML:

<div id="1" class="divs" onclick="hide(this)"></div>
<div id="2" class="divs" onclick="hide(this)"></div>
<div id="3" class="divs" onclick="hide(this)"></div>
<div id="4" class="divs" onclick="hide(this)"></div>
<div id="5" class="divs" onclick="hide(this)"></div>

JavaScript Function:

function hide(obj){
    var divs = document.getElementsByClassName("divs");
    for(var i = 0; i < divs.length; i++){
        if(obj != divs[i]){
            divs[i].style.display = "none";
        }
    }
}

Answer №3

One way to achieve this is through the following code snippets:

HTML

<div id="1" class="boxes" onclick="hideContent(this)">q</div>
<div id="2" class="boxes" onclick="hideContent(this)">w</div>
<div id="3" class="boxes" onclick="hideContent(this)">e</div>
<div id="4" class="boxes" onclick="hideContent(this)">r</div>
<div id="5" class="boxes" onclick="hideContent(this)">7</div>

JavaScript

<script>
function hideContent(element){
    var divElements = document.getElementsByClassName("boxes");
    for(var j = 0; j < divElements.length; j++){
        if(element != divElements[j]){
            divElements[j].style.display = "none";
        }
    }
}
</script>

Answer №4

Check out this simple demonstration to see how you can achieve the desired effect using CSS:

window.onload = () => {
 
  var divs = document.getElementsByClassName('divs');

  for(let div of divs) {
    div.onclick = (e) => {
     for(let visibleDiv of divs) {
              if(visibleDiv != e.target) {
              visibleDiv.style.display = "none";
              }
          }
      }
  }
  
}
.container {
    display: flex;
    justify-content: space-between;
}

.divs {
    width: 50px;
    height: 50px;
    background-color: #e67e22
}
<div class="container">    
    <div id="1" class="divs"></div>
    <div id="2" class="divs"></div>
    <div id="3" class="divs"></div>
    <div id="4" class="divs"></div>
    <div id="5" class="divs"></div>
</div>

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

Guide to setting up a node.js server that serves HTML files with CSS styling

I am currently working on setting up a simple node.js server for my HTML using http and express. Everything is functioning properly, but the CSS is not displaying as expected. Here is the code snippet for my server setup: const express = require("express ...

Showing an array in angular.js

When sending data to a PHP file, the file processes it and performs an SQL search, returning a list of names in a for each statement. For example: Ryan, Jack, Billy, Sarah. However, when echoing the response in Angular, all the names are joined together l ...

Transforming JSON object to an array of arrays using JavaScript

Attempting to extract specific values from a JSON object and store them in an array can be quite tricky. Below is an example of what this process might look like: Example: var obj = { "1":{"class":2,"percent":0.99,"box":[0.2,0.3,0.4,0.5]}, "2 ...

What is the best way to load specific CSS in an rhtml file?

In the world of website development, we often find several pages that are generated from the same layout.rhtml file. Along with a global css file, each page may also have its own unique css file - such as page1.css for page1.rhtml and page2.css for page2.r ...

MongoDB was successfully updated, however the changes are not being displayed on the redirected

I have implemented the delete action in Node/Express as a web framework, where it is structured within a higher-level route: .delete((req, res) => { db.collection('collection-name').findOneAndDelete({ topic_title: req.body.topic_title}, ...

Displaying CSS image slideshow images side by side

Currently I am a student studying the fundamentals of HTML and CSS. My latest project involved creating a website showcasing my work from digital arts class, complete with a simple CSS slideshow. The original intention was to have each image displayed on i ...

How to adjust background size for Iphone4 and Iphone5 simulators using only HTML5 and CSS3 code

Creating an HTML5 app for iPhone4 and 5 with a texture-rich background. I'm facing an issue where the texture image gets scaled and only the central part is visible, even though the image size is 640x960 and 640x1136. I've tried adding @2x at the ...

The variables in Next.js reset every time I navigate to a new page

Looking for a way to share a variable between pages in my Next.Js application, I have the following setup in my _app.js file: import { useState } from 'react'; const CustomApp = ({ Component, pageProps }) => { // Variables const [testVa ...

Material UI: Easily adjusting font size within Lists

When developing forms with react js and material UI, I encountered an issue with changing the font size within lists to achieve a more compact layout. The code fontSize={10} didn't seem to have any effect regardless of where I added it. Is there a wa ...

What is the proper way to display the date and time 2021-11-14T18:30:00.000+00:00?

Here is my ts file code: mydate: Date = new Date('2021-11-14T18:30:00.000+00:00'); However, I want the date to be in this format:- 07-July-2022 If anyone can assist with achieving this format, it would be greatly appreciated. Thank you! ...

What is the best way to display every comment and response using console.log()?

Currently, I am developing a commenting system where users can leave comments and reply to existing comments. In the MySQL database image Both images depict the same scenario. In my highlighted text in yellow, it should read comments[0] instead of comment ...

I am interested in using the split method to separate and then mapping an object in JavaScript

Need assistance on separating an array using the split method. The array contains objects with properties such as name, course1, course2, and course3. Only the courses with text in their content along with a plus sign should be separated into an array usin ...

Methods for adjusting columns and rows in HTML5 tables

As I was preparing to create a compatibility guide, I noticed that the HTML code consisted of a table. While tables are effective for displaying data, they can be cumbersome to edit frequently. What tools are available to quickly and cleanly edit an exist ...

Position a div off-center using CSS styling

Currently, I am utilizing a flexbox to center a div inside another div, akin to a dialog window that pops up at the center of the screen when required. The functionality is sound, but aesthetically it would be more pleasing if the space above and below th ...

Styling CSS variables uniquely

I have limited knowledge of HTML and CSS, so I am unsure how to search for a similar post on StackOverflow. My apologies if this is a duplicate question. I am looking to achieve the following: margin-horizontal { margin-left: value; margin-right: va ...

Typescript's way of mocking fetch for testing purposes

I have a query regarding the following code snippet: import useCountry from './useCountry'; import { renderHook } from '@testing-library/react-hooks'; import { enableFetchMocks } from 'jest-fetch-mock'; enableFetchMocks(); i ...

Variable declared in $scope suddenly losing its definition

Within my directive controller, I've implemented a $watch function as follows: $scope.$watch(function () { return service.abc; }, function(newVal, oldVal) { $scope.abc = {abc: newVal}; }); However, I've encountered issues with the variabl ...

Adding a class to a field tag in a Django form: A step-by-step guide

Is there a way to add a bootstrap class to the label of an input field in a form? I know how to add classes to the input field itself, but I haven't been able to find a guide on adding a class to the label within the form declaration. Can anyone provi ...

Error: Module specifier "react-router-dom" could not be resolved. Relative references should start with either "/", "./", or "../"

I encountered an error message after executing the command npm run preview: Uncaught TypeError: Failed to resolve module specifier "react-router-dom". Relative references must start with either "/", "./", or "../". ...

Is it more effective to be precise when choosing IDs in CSS?

If you have a unique identifier on a div element called main, how should you reference it in CSS - with div#main or just #main? What is considered best practice? Considering that only one element can have a specific id, using div#main essentially duplicat ...