Nithin Krishna
Nithin Krishna

Reputation: 25

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.

Upvotes: 1

Views: 24

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115272

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>

Upvotes: 1

guradio
guradio

Reputation: 15565

$(document).ready(function() {
  $('.openingApply').click(function() {
    var jobcode = $(this).closest('div').find('.jobcode').text();
    console.log(jobcode);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.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>

  1. You need to get the Parent Div using .closest()
  2. Use .find() to get the span

In your code you are looking for a sibling of the element with class openingAply but it has not sibling

Upvotes: 1

Related Questions