Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide all elements that come after the nth element

Tags:

html

jquery

After the 4th <a> element is found, how would I .hide() the rest? Below is the code I've written so far:

<script src="http://code.jquery.com/jquery-latest.js"></script>

<script>
    $(document).ready(function() {
        if($('a').length >= 4) {
            window.alert('4 or more');
        }
    });
</script>

<a>test </a><br>
<a>fed </a><br>
<a>fdes </a><br>
<a>grr </a><br>
<a>rerf </a><br>
<a>dferf </a>

Any ideas?

like image 861
Michael Grigsby Avatar asked Jun 28 '12 22:06

Michael Grigsby


3 Answers

Use :gt(index) selector:

$('a:gt(3)').hide();

Or the faster slice function:

$('a').slice(4).hide();

Live DEMO

Because :gt() is a jQuery extension and not part of the CSS specification, queries using :gt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").slice(index) instead.

like image 143
gdoron is supporting Monica Avatar answered Oct 19 '22 06:10

gdoron is supporting Monica


CSS solution

ul li:nth-child(n+5) {  
    display: none
}

http://jsfiddle.net/mckanet/Sp6yE/

like image 22
mckanet Avatar answered Oct 19 '22 07:10

mckanet


As simple as that:

$("a:gt(3)").hide();

DEMO: http://jsfiddle.net/gmrvK/

like image 25
VisioN Avatar answered Oct 19 '22 05:10

VisioN