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

JavaScript's multiple inheritance concept

In the realm of JavaScript, there exists a class that seeks to 'inherit' various objects and their methods. var A = function (a,c){}; var N = { properties1: function(){}; }; var M1 = { properties2: function(){}; }; var M2 = { ...

I can't figure out why I'm receiving a TypeError stating that onSuccess is not a function within my AngularJS service

Utilizing an angularjs service that utilizes restangular for API calls. angular.module('app.userService', []) .factory('userService', ['localStorageService', '$rootScope', 'Restangular', func ...

Use JavaScript to create a new window and load the HTML content from an external URL

Just starting out with HTML and Javascript I'm trying to use JavaScript to open a window and load content from an external source. I attempted using document.write(), but it only works when I hardcode the HTML as input. Any suggestions on how to get ...

Gaps separating frames

<!Doctype html> <html> <frameset rows="26%,24%,*" noresize border="0" frameborder="no" framespacing="0"> <frame src="frame_a.html" target="_self" name="logo" scrolling="auto"> <frame src="frame_b.html" target="_self" name="menu" ...

Ways to verify the presence of users in the Database

I have successfully retrieved the data with the code below, but I am encountering issues with my script's if and else statements. Any tips or advice on how to improve this functionality? server.post('/like', (req, res,next) => { var ...

How can we use Python and Selenium to retrieve the text from HTML that includes the <p> tag?

I have a simple question that I hope you can help me with. I'm not feeling well and struggling to complete my presentation because my brain just isn't functioning properly. Here is the HTML code in question: <p> <b>Postal code:& ...

Tips for preventing Razor from interpreting special characters as HTML code

I'm encountering an issue with special characters displaying as HTML codes on the page I'm working on. The content is retrieved from a database and shown in readonly input boxes. For example, & is displayed as &. How can I ensure that the ...

Can the text within the <h3> element be displayed on top of the inline image without the use of <span> tags or background images?

Can the text inside an <h3> tag be displayed over an image without using <span> and images in the background? HTML <h3>sample caption 1<img alt="" src="banner4.jpg" /></h3> CSS h3{ } h3 img { } ...

Guide on transferring files between Node.js/Express servers from receiving files at Server A to sending files to Server B

Currently, I'm tackling node.js express servers and I've hit a roadblock! Despite my efforts to scour the documentation and other resources, I can't seem to find the right solution. Here's what I need to accomplish: Receive 2-3 PDF ...

Aligning two lines next to a radio button using HTML and CSS

I'm facing a challenge where I want to align two lines in the middle of a radio button. Despite my efforts, I am able to line up the top line but struggling with the bottom one. I prefer not floating the radio button as it's being styled using a ...

How can we implement :focus-within styling on Material-UI Select when the input is clicked?

I am currently implementing a Select component inside a div element: <div className="custom-filter custom-filter-data"> <DateRangeIcon className="search-icon"/> <FormControl variant='standard& ...

Exploring ways to assign a value to an HTML element utilizing Jquery in combination with ASP.NET MVC 4 complex model information

Within an ASP.NET MVC 4 view, I am utilizing data from a Model to populate various HTML elements. The model is used in the view to showcase values like: <div>@Model.Category.Name</div> etc... However, there is a specific div tag <div id="D ...

Choose ng-change within the table

I've searched everywhere for an answer to this, but I couldn't find it. I have a table that contains select and date input fields. <table id="tblCorrAction" class="table table-bordered table-striped table-hover table-condensed"> <t ...

Looking for a feature where users can easily update their profile using an interactive edit button

I'm currently working on a website project and one of the features I'm tackling is the user's profile page. My objective is to create an edit button within the page that allows the user to modify their name, username, email, and update their ...

The issue arises when the logout component fails to render even after the user has been authenticated. This problem resembles the one discussed in the React Router

While attempting to run the react-router docs example on the browser, I encountered an issue with the AuthButton component. The problem arises when the isAuthenticated value changes to true but the signOut button fails to display. import React from ' ...

JavaScript is experiencing an error where it cannot define a function, rendering it unable to generate a JSON object due to its inability to recognize that the

I've created a JavaScript script function that holds cart items for ordering food. This function takes two parameters: ID and price. Here is a snippet of my script file: <script> function addtocart(mitem, mprice) { var price = ...

Issues with routeparams are preventing ng-repeat from functioning properly, without any response or resolution

For my shoppingCart project, I am working on dynamically bringing data into views. I am using routeParams in template.html but facing an issue. The data is arriving normally as checked via ng-href="#/store/{{something.name}}/{{ child.name }}" but it isn&ap ...

Ways to initiate state transition from child component to parent component using React Hooks?

In the parent component, I have the following: const [updateQuantity, quantity] = useState(1); const handleChangeQuantity = e => { console.log(e.target.value); console.log("TEST"); updateQuantity(e.target.value); }; I the ...

Fixed-positioned elements

I'm facing a small issue with HTML5 that I can't seem to figure out. Currently, I have a header image followed by a menu div containing a nav element directly below it. My goal is to make the menu div stay fixed when scrolling down while keeping ...

Ensure that the heading cells in the table header (thead) are properly

Struggling with aligning the thead with the td in the tbody? I attempted adjusting the thead using display: table-header-group;, but discovered that padding doesn't work on 'table-header-group'. This led me to try adding padding-left to my t ...