When I click on the A1-810 or A1-820 Link.
Output Comes Like this
A1-810
ICONIA A-SERIES
A1-810
A1-820
Now the HTML Nav links are a little complicated actually there are more than 200 links in the navbar but I have copied a little code so that you can understand.
JavaScript
x
7
1
$(document).ready(function() {
2
$("li").click(function() {
3
var a = $(this).text();
4
console.log(a)
5
return;
6
});
7
});
JavaScript
1
23
23
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<ul class="list-unstyled">
3
<li class="dropdown"><a href="#" class="dropdown-toggle">ICONIA A-SERIES</a>
4
<ul class="list-unstyled">
5
<li><a href="#">A1-810</a></li>
6
<li><a href="#">A1-820</a></li>
7
</ul>
8
</li>
9
<li class="dropdown"><a href="#" class="dropdown-toggle">ICONIA B-SERIES</a>
10
<ul class="list-unstyled">
11
<li><a href="#">B1-710</a> </li>
12
<li><a href="#">B1-720</a> </li>
13
</ul>
14
</li>
15
<li class="dropdown"><a href="" class="dropdown-toggle">LIQUID</a>
16
<ul class="list-unstyled">
17
<li><a href="">A1-S100</a> </li>
18
<li><a href="">Z200</a> </li>
19
</ul>
20
</li>
21
</div>
22
</li>
23
</ul>
Advertisement
Answer
You attach the event listener to the LI instead of the A
The LI.text() will show all children of that LI
When you attach to the A instead the content of the clicked anchor is shown also use preventDefault so the link is not followed
JavaScript
1
7
1
$(document).ready(function() {
2
$(".list-unstyled a").on("click", function(e) {
3
e.preventDefault(); // don't follow the link
4
var a = $(this).text();
5
console.log(a)
6
});
7
});
JavaScript
1
23
23
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<ul class="list-unstyled">
3
<li class="dropdown"><a href="#" class="dropdown-toggle">ICONIA A-SERIES</a>
4
<ul class="list-unstyled">
5
<li><a href="#">A1-810</a></li>
6
<li><a href="#">A1-820</a></li>
7
</ul>
8
</li>
9
<li class="dropdown"><a href="#" class="dropdown-toggle">ICONIA B-SERIES</a>
10
<ul class="list-unstyled">
11
<li><a href="#">B1-710</a> </li>
12
<li><a href="#">B1-720</a> </li>
13
</ul>
14
</li>
15
<li class="dropdown"><a href="" class="dropdown-toggle">LIQUID</a>
16
<ul class="list-unstyled">
17
<li><a href="">A1-S100</a> </li>
18
<li><a href="">Z200</a> </li>
19
</ul>
20
</li>
21
</div>
22
</li>
23
</ul>