Pavel Marian Pavel Marian - 4 months ago 20
jQuery Question

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
?

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()