I am just starting JS, so this may be a stupid question. I want to make a dropdown, where if you pick one option the related paragraph would be visible. I didn’t really know how to start this so I created the cars function to make the “e38value” paragraph visible when clicking the e38 button, but nothing happens when I click on it, and I have no clue why. If someone knows a better way doing this and it is not so complicated and a beginner could understand it I would be very happy if you could share it with me.
JavaScript
x
8
1
var e38 = document.querySelectorAll('e38value')
2
3
function cars() {
4
document.querySelectorAll('e38').onclick = function() {
5
console.log('clicked');
6
e38.classList.toggle("e38hidden");
7
}
8
}
JavaScript
1
3
1
.e38hidden {
2
display: none;
3
}
JavaScript
1
34
34
1
<nav>
2
<menu>
3
<menuitem id="kocsid">
4
<a>Amilyen kocsid van</a>
5
<menu>
6
<menuitem id="Audi">
7
<a>Audi</a>
8
<menu>
9
<menuitem><a>Audi</a></menuitem>
10
<menuitem><a>Audi</a></menuitem>
11
<menuitem><a>Audi</a></menuitem>
12
<menuitem><a>Audi</a></menuitem>
13
</menu>
14
</menuitem>
15
<menuitem id="BMW">
16
<a>BMW</a>
17
<menu>
18
<menuitem><a class="e38">750 e38</a></menuitem>
19
<menuitem><a>760 e65</a></menuitem>
20
<menuitem><a>M3 e46</a></menuitem>
21
<menuitem><a>M3 e62</a></menuitem>
22
</menu>
23
</menuitem>
24
<menuitem id="Dodge">
25
<a>Dodge</a>
26
<menu>
27
<menuitem onclick=""><a>Dodge</a></menuitem>
28
<menuitem><a>Dodge</a></menuitem>
29
<menuitem><a>Dodge</a></menuitem>
30
<menuitem><a>Dodge</a></menuitem>
31
</menu>
32
</menuitem>
33
</nav>
34
<p id="e38value" class="e38hidden">e38 value</p>
Advertisement
Answer
there are probably other better ways to acomplish that but here is how to fix you script:
JavaScript
1
11
11
1
function cars() {
2
document.querySelectorAll('.e38').forEach(function(e) {
3
e.onclick = function(evt) {
4
console.log('clicked', evt.target.innerHTML);
5
document.getElementById("e38value").classList.toggle("e38hidden");
6
}
7
})
8
}
9
10
cars();
11
Note:
- You need to call
cars()
to actually initialise the events. - The selector should be “.e38” which means all elements with the
e38
class - You need to call
forEach
as the querySelector returns an array of elements (in that case with only one element) - The click event can be used to locate the target (where it was clicked).
Here is a fiddle: https://jsfiddle.net/b9728Lmk/1/
Does that solve the problem?