Skip to content
Advertisement

why am I getting text of all the links instead of one that is clicked by .text() function

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.

$(document).ready(function() {
  $("li").click(function() {
    var a = $(this).text();
    console.log(a)
    return;
  });
});
<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>
  </div>
  </li>
</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

$(document).ready(function() {
  $(".list-unstyled a").on("click", function(e) {
    e.preventDefault(); // don't follow the link
    var a = $(this).text();
    console.log(a)
  });
});
<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>
  </div>
  </li>
</ul>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement