I have a list of divs that all have class "leftNav". When a user clicks some arrow (previous), i want to grab the previous div and mark it. Using .prev('.leftNav') or .prevAll('.leftNav') doesnt seem to work. If user is currently on 15 and clicks previous, I want the html from 14.
$('.lastProduct').click(function() {
$('.leftNav').each(function() {
if ($(this).hasClass('selected')) {
var html = $(this).prevAll().html();
//Also tried - var html = $(this).prev().html();
//Also tried - var html = $(this).prev('.lastNav').html();
//Also tried - var html = $(this).prevAll('.lastNav').html();
alert(html);
}
})
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='row'>
<div class='lastNav' id='13'>13</div>
</div>
<div class='row'>
<div class='lastNav' id='14'>14</div>
</div>
<div class='row'>
<div class='lastNav selected' id='15'>15</div>
</div>
<div class='row'>
<div class='lastNav' id='16'>16</div>
</div>
<input type='button' class='lastProduct' value='Previous'>
all of those attempts result in "undefined"
What am I missing?
CodePudding user response:
Assuming the mismatch of the leftNav
and lastNav
classes in your code is just a typo, then you don't need an each()
loop here.
You can directly select the .selected
instance and traverse the DOM to find the parent .row
using closest()
. From there you can use prev()
and find()
to target the relevant .lastNav
element before updating the classes on each of them.
$('.lastProduct').on('click', function() {
const $current = $('.leftNav.selected');
const $row = $current.closest('.row');
const $prev = $row.prev().find('.leftNav');
if ($prev.length) {
$current.removeClass('selected');
$prev.addClass('selected');
const prevText = $prev.text();
console.log(prevText);
}
})
.selected {
color: #C00;
font-weight: 900;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div >
<div id="13">13</div>
</div>
<div >
<div id="14">14</div>
</div>
<div >
<div id="15">15</div>
</div>
<div >
<div id="16">16</div>
</div>
<button type="button" >Previous</button>