Reputation: 101
I need to change css display
value of items inside div using jQuery.
What I need to do is, get number of items inside the div element. (Ex- li elements).
If number of li
elements inside the div is more than 6, I need to set display:none
css value to them, while first 6 li
items remain display:block
How can I do that?
I can get number of li elements inside div by using this code,
$(window).ready(function () {
var itemCount = 1;
if ($(window).width() < 768) {
if ($('#my-div li').length > 6) {
var k = $('#my-div li').length;
alert("no of items =" + k);
}
}
});
How can I achieve this?
Upvotes: 0
Views: 191
Reputation: 705
$(document).ready(function(){
$("ul li:gt(5)").hide();
//List elements with an index > 5
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
</ul>
Upvotes: 1
Reputation: 4590
Another approach using jQuery selector :gt
$('#my-div li:gt(5)').hide(); //Index starts from 0 so 5 is 6
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul id="my-div">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
</ul>
Upvotes: 1
Reputation: 4366
Here you got a very easy way to show only the first 6 elements with slice() method, check this:
if($('#my-div > li').size() > 6){
$('#my-div > li').slice(6).hide()
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="my-div">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
</ul>
Upvotes: 2
Reputation: 27041
You can use $('#my-div li').not(":lt(6)").hide()
to show the first 6 li
in your div.
Demo
$(window).ready(function() {
var itemCount = 1;
if (true) { // changed < to > for the example
if ($('#my-div li').length > 6) {
var k = $('#my-div li').length;
alert("no of items =" + k);
$('#my-div li').not(":lt(6)").hide()
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my-div">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</div>
Upvotes: 4
Reputation: 2833
You can loop the list and hide it if the index is more than N. Index start at 0
$('.container > li').each(function(i, e) {
if (i >= 6) { $(this).hide() }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="container">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
</ul>
Upvotes: 1