thank_you
thank_you

Reputation: 11107

Selecting group of children with all the same element tag

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.

http://jsfiddle.net/zTCFe/4/

<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

Answers (5)

Matt Kieran
Matt Kieran

Reputation: 4220

You could also just use CSS for this

li:nth-child(-1n+2) {
    background: yellow;
}

Upvotes: 0

jfriend00
jfriend00

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

Matthew Blancarte
Matthew Blancarte

Reputation: 8301

As an alternative, you can also use .slice()

$('#div').children().slice(2).hide();

http://api.jquery.com/slice/

Upvotes: 1

epascarello
epascarello

Reputation: 207527

Use the :gt() selector to select them

Upvotes: 1

Gromer
Gromer

Reputation: 9931

You were almost there:

$('#div').children(':gt(1)').hide();

More on the :gt selector.

http://jsfiddle.net/gromer/Tdue6/1/

Upvotes: 3

Related Questions