If I click on the link A1-810 I am getting text A1-810 in anchortext variable. Now I want is when I click on A1-810 I should also get text ICONIA A-SERIES in parenttext or another variable
if A1-810 link is clicked I am getting output as
A1-810
Now I want output as
A1-810
ICONIA A-SERIES
Jquery code to get the text of the link.
$(document).ready(function() { $(".list-unstyled a").on("click", function(e) { e.preventDefault(); // don't follow the link var anchortext = $(this).text(); var parenttext; console.log(anchortext) }); });
HTML CODE.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="list-unstyled"> <li class="dropdown"><a href="#" class="dropdown-toggle">ICONIA A-SERIES</a> <ul class="list-unstyled"> <li><a href="#">A1-810</a></li> <li><a href="#">A1-820</a></li> </ul> </li> <li class="dropdown"><a href="#" class="dropdown-toggle">ICONIA B-SERIES</a> <ul class="list-unstyled"> <li><a href="#">B1-710</a> </li> <li><a href="#">B1-720</a> </li> </ul> </li> <li class="dropdown"><a href="" class="dropdown-toggle">LIQUID</a> <ul class="list-unstyled"> <li><a href="">A1-S100</a> </li> <li><a href="">Z200</a> </li> </ul> </li> </ul>
Advertisement
Answer
You can do it like this.
var parenttext = $(this).closest("ul").prev("a").text();
Use .closest("ul")
to travel up to find the first ul
.
Then use .prev("a")
to get the previous sibling of the element type a(link)
.
Demo
$(document).ready(function() { $(".list-unstyled a").on("click", function(e) { e.preventDefault(); // don't follow the link var anchortext = $(this).text(); var parenttext = $(this).closest("ul").prev("a").text(); console.log(anchortext,parenttext) }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="list-unstyled"> <li class="dropdown"><a href="#" class="dropdown-toggle">ICONIA A-SERIES</a> <ul class="list-unstyled"> <li><a href="#">A1-810</a></li> <li><a href="#">A1-820</a></li> </ul> </li> <li class="dropdown"><a href="#" class="dropdown-toggle">ICONIA B-SERIES</a> <ul class="list-unstyled"> <li><a href="#">B1-710</a> </li> <li><a href="#">B1-720</a> </li> </ul> </li> <li class="dropdown"><a href="" class="dropdown-toggle">LIQUID</a> <ul class="list-unstyled"> <li><a href="">A1-S100</a> </li> <li><a href="">Z200</a> </li> </ul> </li> </ul>