AppRoyale AppRoyale -4 years ago 129
jQuery Question

jQuery get Text of parent in list

I have the following list



$(document).ready(function() {
$('li').click(function(e) {
alert($(e.target).children().remove().end().text());
alert($(e.target).siblings('span:first').text());
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<span>foo1</span>
<span style="visibility: hidden">bar1</span>
</li>

<li>
<span>foo2</span>
<span style="visibility: hidden">bar2</span>
</li>

<li>
<span>foo3</span>
<span style="visibility: hidden">bar3</span>
</li>
</ul>





I would like to extract "foo1" and "bar1" at the same time in different values. The function above looks really weird. Could someone find a better approach?

Could you adjust my jQuery function please?

Answer Source

You should try this code:

$(document).ready(function() {
  $('li').click(function() {
    console.log('span #1', this.children[0].innerHTML);
    console.log('span #2', this.children[1].innerHTML);
  });
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download