another option besides the nextElementSibling

I have a unique code that applies a style to the following div when another div is clicked, using nextElementSibling.

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    console.log(panel)
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
}
<div class="accordion">
  <p>Resources</p>
</div>
<div class=panel ">
 Test message
</div>

This triggers a style change on the div with the class panel. I want to move the class accordion from the div to the p tag.

Here's how it should look:

<div>
  <p class="accordion">Resources</p> 
</div>
<div class= panel">
  Test message
</div>   

Now that accordion is no longer next to panel, how can I target the panel?

Answer №1

When the p element becomes a child of the div that is a sibling to .panel, you can utilize the parentElement method to navigate back to that level in the DOM before using nextElementSibling. Here's how it can be done:

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.parentElement.nextElementSibling;
    
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
}
.panel { display: none; }
.active { color: #C00; }
<div><p class="accordion">Resources</p></div>
<div class="panel">Test message</div>

<div><p class="accordion">Resources</p></div>
<div class="panel">Test message</div>

<div><p class="accordion">Resources</p></div>
<div class="panel">Test message</div>

It's worth mentioning that if support for IE is not needed, there are more modern techniques available to achieve the same JavaScript functionality in a more concise way:

document.querySelectorAll('.accordion').forEach(el => {
  el.addEventListener('click', e => {
    let accordion = e.target;
    accordion.classList.toggle('active');
    accordion.parentElement.nextElementSibling.classList.toggle('show');
  });
});
.panel { display: none; }
.panel.show { display: block; }
.active { color: #C00; }
<div><p class="accordion">Resources</p></div>
<div class="panel">Test message</div>

<div><p class="accordion">Resources</p></div>
<div class="panel">Test message</div>

<div><p class="accordion">Resources</p></div>
<div class="panel">Test message</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

Encountering an issue in React: Uncaught ReferenceError - require function not recognized

I am currently working on a project that utilizes both react and node (express). When I include react using src="https://unpkg.com/react@16/umd/react.development.js", everything works fine with JSX in the project. However, when I attempt to import like thi ...

Is it possible to retrieve the selected DataList object in Angular 10?

I encountered an issue while creating an Input field with DataList. My goal was to retrieve the entire object associated with the selected option, but I could only access the selected value. Previous suggestions mentioned that DataList items should be uniq ...

Container struggling to contain overflowing grid content items

While creating a grid in nextjs and CSS, I encountered an issue. Whenever I use the following code: display: grid; The items overflow beyond the container, even though I have set a maximum width. Instead of flowing over to the next row, the items just kee ...

What is the best way to simulate fetch in Redux Async Actions?

When writing tests in the Redux Writing Tests section, how does store.dispatch(actions.fetchTodos()) not trigger the fetch method when store.dispatch is directly calling actions.fetchTodos? The issue arises when trying to run similar code and encountering ...

Customizing the Class of a jQuery UI ui-autocomplete Combobox Container

Is there a way to customize the ui-autocomplete div by adding a custom class? I have several autocomplete widgets on my webpage, and I need to style their drop-downs differently. Since editing the ui-autocomplete class directly is not an option, I am wor ...

Eliminate the presence of core-js in the nextjs bundle

Currently, I am tackling the challenge of minimizing bundle sizes in my Next.js project. One particular aspect that caught my attention is the inclusion of a core-js bundle for polyfills. This adds an extra 50KB to the size of the main bundle, which I aim ...

Html5 declares that the statuses of values are not defined

In a chrome extension, I am encountering an issue with the following code: var DB = openDatabase('CMPDB', '1.0', 'Database for CMP', 4 * 1024 * 1024); LoadFromDB(); function LoadFromDB() { DB.transaction( function(t ...

Tips for integrating angular signature functionality using fabricjs in the latest version of Angular (Angular 11)

After struggling to make paperjs and the angular-signature library work together, I was at my wit's end. But then, I stumbled upon a different solution that proved to be much better. I realized that posting the solution under the appropriate question ...

Stylish popup image with a link to an external source

Currently, I am utilizing Fancybox 3 and Cookie in order to display hidden content once the page has finished loading. The concealed content consists of both an image and an external link. I am encountering difficulties with regards to the functionality ...

What is the best method to retrieve text from a <span> element within an <li> element nested inside a <ul> using BeautifulSoup?

I need help extracting the content from the Here’s what’s new section on this page. Specifically, I am trying to capture everything between In the coming weeks and general enhancements. After inspecting the code, I noticed that the <span> elemen ...

An effective way to verify if a record has been successfully updated is by utilizing Sequelize's

Within this snippet of code, I made an update to a specific record in the IPAdress model. What is the best way for me to verify if the record has been successfully updated or not? let IPAdress = await model.IPAdress.update(data,{ where: { id } }); ...

What steps do I need to take to integrate the turn.js JavaScript library with a Vue.js and Laravel project?

I am a Vuejs beginner currently working on a project that involves both Vuejs (front end) and Laravel (Backend). I have been trying to integrate the JQuery library turn.js into my project, but I keep encountering errors. While I have managed to run jQuery ...

Error encountered while building with Next.js using TypeScript: SyntaxError - Unexpected token 'export' in data export

For access to the code, click here => https://codesandbox.io/s/sweet-mcclintock-dhczx?file=/pages/index.js The initial issue arises when attempting to use @iconify-icons/cryptocurrency with next.js and typescript (specifically in typescript). SyntaxErr ...

Limit Content to be contained within a Bootstrap Container/Div

How can I shrink the content inside a container without distorting images? When the screen size decreases, all the images and content inside start to lose their alignment and sizes begin to change. I am aware that this may make the content harder to see. ...

"The interconnection between NetBeans, jQuery, and AJAX is

My issue is with a Netbeans 7.4 (also tried 7.3) project involving PHP and JavaScript where breakpoints do not work in jQuery ajax loaded pages that contain included JavaScript. I have no problem with PHP or top-level JavaScript, but for example: In index ...

The combination of Heroku (Cedar) with Node, Express, and Jade is causing issues with the client-side javascript files in a subdirectory. While they work fine locally with foreman and

As a newcomer to node and Heroku, I am facing what seems like a simple permission issue. Despite my efforts, I am unable to pinpoint the exact source of the problem. In a sub-directory located one level beneath my root directory where the web.js file is s ...

How to dynamically display a div in Vue.js depending on the attributes of another element

I have a dilemma with my text container. My goal is to collapse the div if the text length exceeds a certain limit, and then display a button that says "...show more". When this button is clicked, the div should expand. Clicking it again should collapse th ...

How come executing a function in the Node.js REPL using )( actually functions?

In JavaScript, why is it possible to call a function like this when tested with node.js: ~$ node > function hi() { console.log("Hello, World!"); }; undefined > hi [Function: hi] > hi() Hello, World! undefined > hi)( // Why does this work? Hell ...

Oops! The Route.post() function is looking for a callback function, but instead, it received an [object Object

Looking to integrate a password reset feature in my web app, but encountering the error mentioned in the title. Here's a snippet of my code: main.js: const router = express.Router(); const AsyncNewPassword = require('./controller/asyncnewpasswor ...

Implementing nested popup windows using Bootstrap

I am facing an issue with my two-page sign-in and sign-up setup in the header of my angular2 project. On the sign-up page, I have a link that should redirect to the sign-in page when clicked, but I am struggling to make it work. Can someone provide guidanc ...