Get value of a h4 selector inside multiple selectors in javascript

I have a ul list in HTML and I am struggling to get the inner text of the li element. I will simplify a little the example to be easy to understand what I am trying to do. I have the following ul with list items:

<ul id="table-history">
    <li class="item">
       <div class="item-row">
           <h4 class="item-title"> A </h4>
       </div>
     </li>

     <li class="item">
       <div class="item-row">
           <h4 class="item-title"> B </h4>
       </div>
     </li>        

     <li class="item">
       <div class="item-row">
           <h4 class="item-title"> C </h4>
       </div>
     </li>
</ul>

I have created a click method in javascript that get triggered when a list item is clicked:

$("#table-history > li").on("click", function () {

        console.log("Clicked");
});

How can I take the text inside the <h4> element ? Is there a way how can I make the click on chain elements/views ?

Answers:

Answer

you can use

$('h4.item-title' , this).text()

$("#table-history > li").on("click", function () {
        
        console.log($('h4.item-title' , this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="table-history">
    <li class="item">
       <div class="item-row">
           <h4 class="item-title"> A </h4>
       </div>
     </li>

     <li class="item">
       <div class="item-row">
           <h4 class="item-title"> B </h4>
       </div>
     </li>        

     <li class="item">
       <div class="item-row">
           <h4 class="item-title"> C </h4>
       </div>
     </li>
</ul>

Note: It will be better to use .trim() to avoid white spaces

$('h4.item-title' , this).text().trim()
Answer

Try using text():

$("#table-history > li").on("click", function () {
    console.log($(this).text());
});

EXAMPLE

$(document).on('click', '.item', function() {
  alert($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<ul id="table-history">
    <li class="item">
       <div class="item-row">
           <h4 class="item-title"> A </h4>
       </div>
     </li>

     <li class="item">
       <div class="item-row">
           <h4 class="item-title"> B </h4>
       </div>
     </li>        

     <li class="item">
       <div class="item-row">
           <h4 class="item-title"> C </h4>
       </div>
     </li>
</ul>

Answer

you can use this

$("#table-history > li").on("click", function () {

    console.log($(this).find('h4').text());
});
Answer

You can try this simplest method:

$("#table-history > li").on("click", function () {
     alert($(this).text().trim());
});

And Your Final Output

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.