Reputation: 11107
I have a div that contains four paragraph tags. When the page is loaded, I wanted to have the first two paragraphs to be shown then have the follow paragraph elements be hidden, but I have no idea how to do this. For simplicity I set the event to a button versus a document ready event in the jsfiddle example below.
<div id="div">
<p>1 keep me shown</p>
<p>2 keep me shown</p>
<p>3 hide me</p>
<p>4 hide me</p>
</div>
<input type="button" value="press" id="button"/>
<script>
$('#button').click(function () {
$('#div').children().hide();
});
</script>
Upvotes: 1
Views: 113
Reputation: 4220
You could also just use CSS for this
li:nth-child(-1n+2) {
background: yellow;
}
Upvotes: 0
Reputation: 707716
You can use the :gt()
selector:
$("#div p:gt(1)").hide();
Or, you can also use .slice()
to select specific elements from the jQuery object's DOM array:
$("#div p").slice(2).hide();
Upvotes: 1
Reputation: 8301
As an alternative, you can also use .slice()
$('#div').children().slice(2).hide();
Upvotes: 1
Reputation: 9931
You were almost there:
$('#div').children(':gt(1)').hide();
More on the :gt selector.
http://jsfiddle.net/gromer/Tdue6/1/
Upvotes: 3