简体   繁体   中英

Get li Element Text When Click on that Element

I have this code. When I click on any li element then the first alert it shows its value, then show its parent then again that parent and so on. I just want to show the text of the clicked li element. How can I do that?

 $('#container li').on('click', function() { alert($(this).text()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <ul class="xyz"> <li>Grand Parent 1</li> <li> <ul class="xyz"> <li>Parent 1</li> <li>Parent 2 <ul class="xyz"> <li>Child 1</li> <li>Child 2</li> <li>Child 3</li> <li>Child 4</li> </ul> </li> <li>Parent 3</li> <li>Parent 4</li> </ul> </li> </ul> </div> 

Your first issue is that you need to stop the proprgation of the event from the clicked li to the parent li elements. You can call stopPropagation on the passed event handler to do that.

Secondly, I assume you only want to retrieve the child text value of the li , not the text of it's descendants, in which case you would need to use contents()[0] to access it. Try this:

 $('#container li').on('click', function(e) { e.stopPropagation(); var text = $(this).contents()[0].nodeValue.trim(); console.log(text); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <ul class="xyz"> <li>Grand Parent 1</li> <li> <ul class="xyz"> <li>Parent 1</li> <li> Parent 2 <ul class="xyz"> <li>Child 1</li> <li>Child 2</li> <li>Child 3</li> <li>Child 4</li> </ul> </li> <li>Parent 3</li> <li>Parent 4</li> </ul> </li> </ul> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM