0
<span class="info">
    <span> Child 1 </span>
</span>
<span class="info">
    <span> Child 2 </span>
</span>

$('#result').on('click', 'span', function() {
var search = $(this).children(".info").val();

I want to access the text written inside the child element of the clicked element. It does not work with the .val function that wrote above because there is no value. How can I do it with innertext function ?

If the top span is clicked, the value of the search variable should be Child 1, if the bottom span is clicked, its value should be Child 2.

Thank you.

1 Answers1

2

Use .text().

$('#result').on('click', 'span.info', function() {
  let search = $(this).find('span').text();
  console.log(search);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result">
  <span class="info">
    <span> Child 1 </span>
  </span>
  <span class="info">
    <span> Child 2 </span>
  </span>
</div>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • The function works, but it doesn't just take text, it also takes spaces. For this reason, it cannot find the data when querying from MySQL. – Bora Özçağlar Jan 20 '23 at 16:58
  • @BoraÖzçağlar Spaces are part of the text; you have spaces in your HTML, so it is returned. You can use `$(this).find('span').text().trim()` to remove the leading and trailing spaces. – Unmitigated Jan 20 '23 at 17:01