I have this code and i want to alert the value of "first div" when i click the button on the first object and "second div" when i click the button on the 2nd object. .
How will i do it ? thanks :)
$(document).ready(function(e) { $('.clickme').click(function() { var selected = $(this).closest('.rel-wrap').find('.my-div').text; alert(selected); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <div class="main-wrapper"> <div class="rel-wrap"> <input type="button" class="clickme" value="click me"> <div class="my-div"> first div </div> </div> <div class="rel-wrap"> <input type="button" class="clickme" value="click me"> <div class="my-div"> second div </div> </div>
text()
method, not the property next()
, no need of traversing to the parent to get the interested element Demo
$(document).ready(function(e) { $('.clickme').click(function() { var selected = $(this).next('.my-div').text(); alert(selected); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <div class="main-wrapper"> <div class="rel-wrap"> <input type="button" class="clickme" value="click me"> <div class="my-div"> first div </div> </div> <div class="rel-wrap"> <input type="button" class="clickme" value="click me"> <div class="my-div"> second div </div> </div> </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.