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

Ways to hover and efficiently organize components?

My elements are floated with a width of 20%, resulting in 5 elements per line. The current arrangement looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Now, I want to reorganize them vertically as follows: 1 4 7 10 13 2 ...

Controller is not being triggered by Ajax method when there is a decimal value

I am currently working on implementing a time registration feature in my web application. Users can select the project they worked on and enter the number of hours spent on that project. Everything is functioning properly until users start adding half-hou ...

Identifying the relationship between child and parent components in Vue.js

I am new to Vue.js and I am practicing some simple exercises on communication between Vue components. However, I am struggling with understanding who is a child component and who is a parent component. For example, consider the following code snippet: HTM ...

What is the best way to implement momentJS globally in VueJS 2?

Currently working with Vue.js version 2.6.11 Trying to set up in main.js as follows: import moment from 'moment' moment.locale('nl'); Object.definePrototype(Vue.prototype, '$moment', { value: moment }); Encountering an error ...

Obtain the response header variable within a Shiny application

In Apache, the LDAP login is passed to a variable called X-Remote-User in the header: I am unsure how to retrieve this information in my Shiny app. Does anyone have any ideas? Maybe using JavaScript could be a solution? ...

Tips on retrieving JSON data in a Bottle (Python framework) using a Jquery script

I'm currently facing an issue where I am sending a POST request with JSON data using AJAX jQuery, expecting to receive it on my API server built with Bottle. However, the JSON data is being sent from the client side but isn't being received by th ...

Reset the default value of the "Bootstrap Select2" dropdown

I am currently implementing the bootstrap select2 plugin and I need a way to ensure that the default selected value, which is null, gets cleared when selecting other options. HTML snippet: <select class="selectpicker" multiple="" name="maritalstatus[] ...

Countdown Clock for Displaying Parsing Time in C#

On my aspx page, I have a submit button that triggers the parsing of ".txt" files when clicked. The parsing process generates results stored in tables and then redirects the user to another page. However, the issue at hand is that the parsing operation t ...

What causes the discrepancy in the output of `document.documentElement.childNodes` in JavaScript?

While working on my code exercise today, I came across a special case regarding the "document.documentElement.childNodes" property. Originally, I believed it to represent all child nodes within a tag as before. However, when implementing my code, I noticed ...

What is the process for mediating a SWF-Flash file with a PHP mediating, also known as an HTTP-Pseudostreaming script?

I am currently developing a mini context media platform that utilizes HTTP Pseudostreaming. This involves using a PHP script to manage the media file, ensuring proper access and linking to the correct directory. Below are the key components of my code: // ...

Conceal the parent element if there are no elements present within the child element

Look at the markup provided: <div class="careersIntegration__listing" id="careers-listing"> <div class="careersIntegration__accordion"> <div class="careersIntegration__accordion-header"> <span class="careersIntegrat ...

Ensure that adjacent elements operate independently from one another

The code snippet provided above showcases four components: StyledBreadcrumbs, FilterStatusCode, Filter, LinkedTable. The FilterStatusCode component enables users to input search data using TagInput. If the user inputs numerous tags, this component expands ...

`problem encountered when attempting to sanitize HTML through the npm package known as "sanitize-html"`

After researching the documentation, I attempted to use this code snippet: const dirty = '<div>Content</div>'; const clean = sanitizeHtml(dirty); The desired result of 'clean' should be "Content", however it seems that &apo ...

Sending a parameter between files in a React application: a step-by-step guide

I am currently working on a Pokedex website where I have Pokemon cards displaying data from a JSON file. When a user clicks on a card, a modal view appears with more detailed information about that specific card. I need help in ensuring that only the deta ...

utilize a modal button in Angular to showcase images

I am working on a project where I want to display images upon clicking a button. How can I set up the openModal() method to achieve this functionality? The images will be fetched from the assets directory and will change depending on the choice made (B1, ...

Expressing the power of multiple nested routers

Can multiple nested routers be implemented in an Express server? Imagine running a vehicle servicing business and wanting to organize the API into different services, each with its own set of actions: app.use('/clean', cleanRoutes); app.use(&apo ...

Tips on how to stop label text from wrapping onto a new line and only show one line

Working with asp.net mvc, I am encountering an issue where the label text is displaying on two lines instead of one. The expected behavior is for it to appear on a single line. I need the label text to display without wrapping to a new line. For example, ...

Despite providing the correct token with Bearer, Vue 3 is still experiencing authorization issues

I am working on a project that involves Vue 3 with a Node Express back-end server and Firebase integration. On the backend server, I have implemented the following middleware: const getAuthToken = (req, _, next) => { if ( req.headers.authori ...

The functionality of a Vue custom tooltip behaves strangely after clicking the button multiple times

I created this custom tooltip code that automatically closes after 2 seconds when a user clicks on a button, not just hovers over it. Initially, it works perfectly for the first two clicks, but then starts behaving strangely from the third click onwards. ...

Enhancing user experience by highlighting invalid input fields with a red border using client-side HTML5 validation and Bootstrap 5.2

When reviewing the Bootstrap 5.2 validation documentation, https://getbootstrap.com/docs/5.2/forms/validation/ "It has come to our attention that the client-side custom validation styles and tooltips are not accessible at this time, as they are not ...