2



I can not get this code to work.
I am trying to create a function that can listen to click on multiple elements with same class name, and then after click, toggle a specific class name on the next element with a specific class name.

I am trying to use a loop that loops through all the "buttons" (class="click-to-expand") and when you click a specific button, it should loop through the specific divs and toggle a class name on the next element with (class="expand").

Any help would be very appreciated!

var expandArray = document.querySelectorAll('.expand');

document.querySelectorAll('.click-to-expand').forEach(function(i) {
  i.addEventListener('click', function(e) {
    e.target.expandArray[0].classList.toggle("hidden");
  })
});
.hidden {display: none}
<div>
  <div>
    <div class="click-to-expand">+</div>
  </div>
</div>
<div class="expand hidden">asd</div>

<br>

<div>
  <div>
    <div class="click-to-expand">+</div>
  </div>
</div>
<div class="expand hidden">asd</div>

<br>

<div>
  <div>
    <div class="click-to-expand">+</div>
  </div>
</div>
<div class="expand hidden">asd</div>

1 Answer 1

4

You can try this


var expandArray = document.querySelectorAll('.expand');
var buttonArray = document.querySelectorAll('.click-to-expand');

document.querySelectorAll('.click-to-expand').forEach(function(i) {
  i.addEventListener('click', function(e) {
    const clickedBtnIndex = [...buttonArray].indexOf(e.target);
    expandArray[clickedBtnIndex].classList.toggle("hidden");
  })
});

The logic is to find out the index of the button which was clicked and use the same index to find the element in expandArray for which"hidden" should be toggled.

Sign up to request clarification or add additional context in comments.

1 Comment

I did not think about that. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.