Reputation: 25
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
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
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>
In your code you are looking for a sibling of the element with class openingAply but it has not sibling
Upvotes: 1