Nithin Krishna Nithin Krishna - 6 months ago 12
Javascript Question

Get content of a span on button click

I know this is kind of a newbie question and have searched a lot but doesn't solve my issue. i have this following HTML

<div class="col-lg-12 opening">
<span class="openingHead col-lg-4 jobcode">Junior ASP.NET Developer</span>
<a href="#">
<span class="col-lg-1 pull-right text-right openingApply">Apply now</span>
</a>
</div>


and the following js

<script>
$(document).ready(function(){
$('.openingApply').click(function(){
var jobcode=$(this).prevAll('.jobcode').text();
console.log(jobcode);
});
});
</script>


But it just logs undefined .Could you please help me out here. Im still learning jQuery.

Answer

You need to parent first, since .jobcode is sibling to it's parent and not to the span.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col-lg-12 opening">
  <span class="openingHead col-lg-4 jobcode">Junior ASP.NET Developer</span>
  <a href="#">
    <span class="col-lg-1 pull-right text-right openingApply">Apply now</span>
  </a>
</div>
<script>
  $(document).ready(function() {
    $('.openingApply').click(function() {
      var jobcode = $(this).parent().prevAll('.jobcode').text();
      console.log(jobcode);
    });
  });
</script>