Ways to pinpoint a particular division and switch its class on and off?

Consider this scenario, where a menu is presented:

function toggleHiddenContent(tabClass) {
    let t = document.querySelectorAll(tabClass);
    for(var i = 0; i<t.length; i++) {
        t[i].classList.toggle="visible-class";
    }
}
.hidden-content {
    display: none;
}
.visible-class {
    display: block
}
<div>
    <a class="main-holder" onClick="toggleHiddenContent('.main-holder')">Main one</a>
    <div class="hidden-content">Hidden content One</div>

    <a class="main-holder" onClick="toggleHiddenContent('.main-holder')">Main two</a>
    <div class="hidden-content">Hidden content two</div>
</div>

Despite the functionality, it currently toggles all classes. I am aware of the issue, but I am seeking a method to target only the clicked element and not those untouched. Any ideas on how to achieve this using vanilla javascript?

Your assistance would be greatly appreciated.

Answer №1

classList.toggle is actually a function and not something that can be assigned as a property.

Visit this link for more information on classList

You can try the following code snippet:

function toggleHiddenContent(tabClass) {
  let t = document.querySelectorAll(tabClass);
  for (var i = 0; i < t.length; i++) {
    t[i].classList.toggle("visible-class");
  }
}

Based on your example, I recommend making some minor tweaks to improve readability such as enclosing the content in a parent <div> and removing the onClick attribute from HTML. You can view the updated code here:

Check out the fiddle for the changes

The answer provided below mentions using nextElementSibling which eliminates the need to modify your HTML as suggested above.

Answer №2

Here is a suggestion you can try:

function toggleHiddenContent(elem) {
    if (elem.target.nextElementSibling.classList.contains("visible-class")) {
        elem.target.nextElementSibling.className = "hidden-content";
      
    } else {
        elem.target.nextElementSibling.className = "visible-class";   
    }
}
.hidden-content {
    display: none;
}
.visible-class {
    display: block
}
<div>
    <a class="main-holder" onClick="toggleHiddenContent(event)">Main one</a>
    <div class="hidden-content">Hidden content One</div>

    <a class="main-holder" onClick="toggleHiddenContent(event)">Main two</a>
    <div class="hidden-content">Hidden content two</div>
</div>

Answer №3

If you're looking to enhance user experience while also avoiding intrusive JavaScript, consider implementing the following approach:

//Identify and store the elements you wish to interact with in an array:
let myElements = document.getElementsByClassName("main-holder");
//Iterate through the array to add event listeners to each interactive element:
for (let i = 0; i < 10; i++) {
  if (myElements[i]) {
    myElements[i].addEventListener("click", function() {
      //Your custom function:
      toggleHiddenContent("visible-class", i);
    });
  }
}

function toggleHiddenContent(tabClass, target) {
  //Retrieve and store the elements you want to modify in another array:
  let targetElements = document.getElementsByClassName("hidden-content");
  //Use the index from the clicked element to determine which targeted element to modify:
  targetElements[target].classList.toggle(tabClass);
}
.hidden-content {
  display: none;
}

.visible-class {
  display: block;
}
<div>
  <a class="main-holder">Main one</a>
  <div class="hidden-content">Hidden content One</div>

  <a class="main-holder">Main two</a>
  <div class="hidden-content">Hidden content two</div>
</div>

JSFiddle

Should you require further assistance or clarification, please feel free to reach out in the comments below.

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

Auto-scrolling text box cursor movement

My query is quite similar to the topic discussed in this thread on automatic newline in textarea. However, my situation involves multiple textareas with a 1-row attribute, making it seem like writing on air due to the absence of visible borders (I've ...

Make the jQuery toggle() function work like a regular radio button when selecting multiple options at a time

I have recently created two radio buttons using <i> font icons. Previously, I had successfully used the same code to create a checkbox, so I applied it to the radio buttons as well. After fixing the positioning, everything seemed fine when interactin ...

Getting pictures dynamically from the backend with unspecified file types

Greetings to my fellow Stackoverflow-Users, Lately, I was tasked with the requirement of loading images dynamically from the backend into my application. Up until now, it was always assumed that we would only be dealing with SVG images since there was no ...

Increasing a value within HTML using TypeScript in Angular

I'm working with Angular and I have a TypeScript variable initialized to 0. However, when trying to increment it using *ngFor in my .ts file, the increment is not happening (even though the loop is running correctly). my-page.html <div *ngFor=&quo ...

Angular code isn't functioning properly

I recently started coding in Angular.js using WebStorm: <!DOCTYPE html> <html ng-app="store"> <head lang="en"> <meta charset="UTF-8> <title></title> </head> <body ng-app="store"> <script src="bowe ...

Tips on utilizing Blazorise's numeric edit group with grouping functionality

I recently attempted to utilize the numeric edit group separating attribute in Blazorise but encountered issues. According to the documentation, it should be possible to use this feature, however, my attempts were unsuccessful. I would greatly appreciate ...

Is it possible to invoke a computed property within the props of a child component in Vue.js?

In the context of my child and parent components, I have a boolean prop in the child component with a default value of false. When calling the child component within the parent component and setting it based on a computed function that returns a boolean va ...

Learn how to implement media queries using CSS3 with an HTML5 form

Struggling to implement Media Query in my HTML5 form that was styled using CSS. Any assistance would be greatly appreciated. <div class="form"> <form action="Login.jsp" method="post" > <input type="text" name="username" placeholder="usernam ...

Getting React Developer Tools to Function with Webpack

I recently followed a tutorial on how to expose React as a global variable in Webpack using the Expose module. Despite installing the Expose module and adding the appropriate loader configuration in the webpack.config.js file, I am still unable to access R ...

What is the process for activating the Placeholder feature in a Floating Input Field in a React application

Having trouble changing the placeholder value in a Bootstrap-based floating input. I want to display default text as a placeholder and allow users to edit it. Any suggestions? Check out this example on CodeSandbox <div class="form-floating mb-3&qu ...

Encountering the 404 Not Found error when trying to fetch the Next.js API Route from the app

Currently facing difficulties with the routing in Next.js 13's app. Every time I attempt to access it, for instance via Postman, I keep getting a 404 Not Found error. This is my file structure: https://i.stack.imgur.com/ZWrlb.png An example of one ...

The main menu items in jQuery do not display the child sub menu upon clicking

I'm currently in the process of creating a unique mobile menu for my Wordpress website, but I'm facing some challenges when it comes to displaying and hiding the sub-menu items. I've assigned the class name .menu-item-has-children as my sele ...

Tips on retrieving the text content of an HTML element using its tag

Is there a way to retrieve the selected text along with its HTML tags using window.getSelection()? When using window.getSelection(), it only returns plain text such as HELLO. However, I need the text with the HTML tag included, like this <b>Hello< ...

Exploring the power of jQuery's Ajax feature combined with the POST method

I'm facing an issue with two files named basic.php and pptimeline.php. The objective is to choose a value from a combobox in basic.php, process it in pptimeline.php, and then display the result back in basic.php. However, I haven't been able to a ...

The Gulp task is stuck in an endless cycle

I've set up a gulp task to copy all HTML files from a source folder to a destination folder. HTML Gulp Task var gulp = require('gulp'); module.exports = function() { return gulp.src('./client2/angularts/**/*.html') .pipe( ...

Error: The function $(...).froalaEditor is not recognized | This issue is occurring within the $(document).ready(function(){}) block in J

When attempting to set HTML content of the Froala editor within a JSP using $(document).ready(), this error occurs. TypeError: $(...).froalaEditor is not a function | $(document).ready(function(){}) in JSP I read on a GitHub issue that placing jQuery sc ...

Challenges with managing jQuery's .blur() and .focus() events

I am encountering an issue with a form I have created that contains several input fields. When a user clicks on any of the input fields, a hidden div appears with various options related to that field. The user can then select an option from the div, which ...

Show whether the day is even or odd with the JavaScript getDay object

I'm currently working on a task where I need to show the text "Even Day" if the day of the month is 2, 4, 6..., and "Odd Day" for days such as 1, 3, 5, and so on. I attempted to achieve this by setting up an array linked to the getDay object, but unfo ...

The reason CSS properties do not inherit automatically

As I work on designing a straightforward website, I find myself grappling with CSS and particularly inheritance. My objective is to create a side menu where items are stacked vertically: #inner-flex-container { display: flex; flex-direction: column; ...

How can I prevent all products from being displayed when I press the backspace key?

Is there a way to prevent all products from being displayed when the backspace key is pressed? I want the search results to disappear only when the search box is empty. $(document).ready(function(){ $('#product-keyword').on('key ...