Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide last two items in a div

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 divs are not removing.

What am I missing ?

like image 395
Gammer Avatar asked Dec 23 '22 04:12

Gammer


2 Answers

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>
like image 197
Pete Avatar answered Jan 04 '23 03:01

Pete


You need to do $('.showRooms').find('div').slice(-2).remove() as there are three divs 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 divs 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>
like image 30
Ankit Agarwal Avatar answered Jan 04 '23 03:01

Ankit Agarwal