I have the following code , in which I want to hide last two items in a div :
$('.toggleRoom').click(function() {
$('.showRooms').slice(-2).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="showRooms">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
But its not working, The last two div
s are not removing.
What am I missing ?
You need to hide the children of your selected div:
var children = $('.showRooms').children();
$('.toggleRoom').click(function() {
// hide last 2
children.show().slice(-2).hide();
// or use remove if you want them removing instead of hiding:
// children.slice(-2).remove();
});
$('.toggleRoom-1').click(function() {
// hide all but last 2
children.show().slice(0, -2).hide();
// or use remove if you want them removing instead of hiding:
// children.slice(0, -2).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="showRooms">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
<div class="toggleRoom">click to hide last 2</div>
<div class="toggleRoom-1">click to hide all but last 2</div>
You need to do $('.showRooms').find('div').slice(-2).remove()
as there are three div
s inside the div
with class showRooms
so you need to select the last two div
using slice(-2)
.
$('.toggleRoom').click(function() {
$('.showRooms').find('div').slice(-2).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="showRooms">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<button class='toggleRoom'>Click</button>
Based on your comment to remove all div
except last two div
s you need to do:
$('.toggleRoom').click(function() {
var elem = $('.showRooms').find('div');
elem.slice(0, elem.length-2).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="showRooms">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
<button class='toggleRoom'>Click</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With