I am trying to close the other div when I open a new div, But I am using in loop so I used forloop.counter
But it is not working. And when I try to use without forloop.counter or outside the loop then it is working fine, but I want to use inside the for loop.
page.html
JavaScript
x
36
36
1
{% for result in results %}
2
3
<button class="open-div-button" onclick="openDiv-{{forloop.counter}});">Open Div</button>
4
5
<div class="div-content" id="content-{{forloop.counter}}">Content Goes Here</div>
6
7
{% endfor %}
8
9
10
11
<script>
12
13
function openDiv(id) {
14
let model = document.getElementById(`openDiv-${id}`);
15
model.classList.toggle("active");
16
}
17
18
</script>
19
20
<style>
21
22
.content {
23
padding: 10px 20px;
24
display: none;
25
background-color: #f1f1f1;
26
}
27
28
.content.active {
29
padding: 10px 20px;
30
display: block;
31
background-color: #f1f1f1;
32
}
33
34
</style>
35
36
I have also tried using forEach
like :-
JavaScript
1
11
11
1
function openDiv(id) {
2
let model = document.getElementById(`openDiv-${id}`);
3
document.querySelectorAll(`openDiv-${id}`).forEach(function(div) {
4
if (div.id == id) {
5
model.classList.toggle("active");
6
} else {
7
model.classList.toggle("active");
8
}
9
});
10
}
11
but it is not working and it is not showing any error.
What I am trying to do?
I am trying to close
active div when new div is open in for loop.
I have tried many times but it didn’t work. I seen many questions, but unfortunately I didn’t find any of them for forloop.counter
. Any help would be much Appreciated. Thank You in Advance.
Advertisement
Answer
You can do it like this (if forloop.counter
works without problem):
JavaScript
1
34
34
1
{% for result in results %}
2
3
<button class="open-div-button" onclick="openDiv({{forloop.counter}});">Open Div</button>
4
5
<div class="div-content" id="content-{{forloop.counter}}">Content Goes Here</div>
6
7
{% endfor %}
8
<style>
9
.div-content{
10
padding: 10px 20px;
11
display: none;
12
background-color: #f1f1f1;
13
}
14
15
.div-content.active {
16
padding: 10px 20px;
17
display: block;
18
background-color: #f1f1f1;
19
}
20
</style>
21
<script>
22
function openDiv(id) {
23
let model = document.getElementById(`content-${id}`);
24
let currentActive = document.querySelector('.div-content.active');
25
if(currentActive){
26
currentActive.classList.remove('active');
27
}
28
29
if(currentActive != model){
30
model.classList.add("active");
31
}
32
}
33
</script>
34