4

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>
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • Why alert? If it is for debugging, then thats a terrible approach - instead use console.log and similar functions. If its a purpose, im just curious what it could possibly be? ___ W3Schools: http://www.w3schools.com/js/js_debugging.asp ___ Chrome: https://developer.chrome.com/devtools/docs/javascript-debugging ___ Stackoverflow: http://stackoverflow.com/questions/988363/how-can-i-debug-my-javascript-code – Daniel Brose Sep 02 '15 at 04:45
  • Hello @DanielBrose. Yes i use it for debugging . I also use console.log. . –  Sep 02 '15 at 05:38

1 Answers1

3
  1. To get innerText of an element you need to use text() method, not the property
  2. You can use 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>
Tushar
  • 85,780
  • 21
  • 159
  • 179