javascript - How to find the text() when I click on particular element? -
when click on "press me" span text , need "fold2" text()
value. tried add lot of jquery traverse methods in script, can't find perfect one.
because of <li>
including lot of <span>
tag available.
html code:
<li class="favdelparentfold"> <a href="#parentlevel1" data-toggle="collapse" class="" aria-expanded="true"> <span class="caret-right"></span> </a> <span class="folder"></span> <span style="color:red;">fold2</span> <span data-toggle="modal" data-target="#addfavorites_modaldel" class="trashcan">press me</span> <ul class="collapse in" id="parentlevel1" aria-expanded="true"> </ul> </li>
js code
// when click on "press me" text need span value of fold2 $(document).ready(function() { $(".favdelparentfold span").click(function(){ var tr=$(this).closet().find('a').text(); alert(tr);//expecting output "fold2" }); });
working code
via jquery, simplest way (if reason there's no way put class on target):
$('.trashcan').on('click', function(e) { var prev = $(this).prev(); if (prev.length) { alert( prev.text() ); } });
in case, code works if target before source element.
another is, assuming target has class of .target
:
$('.trashcan').on('click', function(e) { var parent = $(this).closest('.favdelparentfold'); if (parent.length) { alert( parent.find('.target').text() ); } });
better have class can move around target , code still work.
Comments
Post a Comment