Read the text inside li tag which is inside a class

Viewed 162

I have the HTML code below and I need to read the text Good which is inside a li tag when a click event occurs using jquery. I have clicked the second div and I need to read the text between its li tag, i.e; Good. There are 22 divs with the same class name and I don't like to add id to all 22 divs. Now, how can I do that using jquery?

HTML

<div class="card" style="width: 15rem;">
  <img src="..." class="card-img-top" alt="...">
  <ul class="list-group list-group-flush">
      <li class="list-group-item">Hello</li>
      <li class="list-group-item">World</li>
  </ul>
</div>

<div class="card" style="width: 15rem;">
  <img src="..." class="card-img-top" alt="...">
  <ul class="list-group list-group-flush">
      <li class="list-group-item">Good</li>
      <li class="list-group-item">Morning</li>
  </ul>
</div>

I have tried doing this but couldn't access the li element. Below is my jquery code

JQUERY

$(".card").click(function(e){
  console.log($(this));
});
1 Answers

Instead of your .card css selector, target only the <li> inside the .card, then use this.text() to get the content of the <li>:

Css selector: .card li

$(".card li").click(function(e){
  console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card" style="width: 15rem;">
  <img src="..." class="card-img-top" alt="...">
  <ul class="list-group list-group-flush">
      <li class="list-group-item">Hello</li>
      <li class="list-group-item">World</li>
  </ul>
</div>

<div class="card" style="width: 15rem;">
  <img src="..." class="card-img-top" alt="...">
  <ul class="list-group list-group-flush">
      <li class="list-group-item">Good</li>
      <li class="list-group-item">Morning</li>
  </ul>
</div>

Related