Keeno
Keeno

Reputation: 1686

jquery selecting specific element and manipulating it

ok, bit of a noob question - and more to satisfy my need to understand WHY i cant do this, or how to do it better....

$("#hi div").hide();
var temp = $("#hi div")[0];
$(temp).show();

This works, fantastic.

$("#hi div")[0].show();

Why doesnt that work! Is there a short hand way to do what I need to do, without having to define a variable?

Upvotes: 2

Views: 133

Answers (3)

hamczu
hamczu

Reputation: 1774

Or even simpler:

$('#hi div:first').hide(); 
$('#hi div:eq(0)').hide(); //the same

Edit: I have looked at jQuery (1.4.2) source and find out:

// .first() = eq(0)
first: function() {
    return this.eq( 0 );
},

// eq(i) wrapper around slide method
eq: function( i ) {
    return i === -1 ?
    this.slice( i ) :
    this.slice( i, +i + 1 );
},
// slice is not simple and pushstack method is quite complicated
slice: function() {
        return this.pushStack( slice.apply( this, arguments ),
            "slice", slice.call(arguments).join(",") );
    },
// so:
$('#hi div').slice(1); // does not work - returns all divs
$('#hi div').slice(-1); // returns first div

PS. I know is little pointless, but I like to know how stuff works "under the hood"

Upvotes: 1

user113716
user113716

Reputation: 322492

When you do [0], you're pulling the first DOM element out of the set of elements in the jQuery object. Because DOM elements don't have a native .show() function it doesn't work.

The reason the first example works is that you're pulling the DOM element out with [0], but then re-wrapping it with a jQuery objected when you do $(temp). You didn't do that for the second.

If you were hoping to target only the first matched element in the jQuery object, use .eq(0) instead, which gives you the DOM element wrapped in jQuery.

var divs = $("#hi div").hide();
divs.eq(0).show(); // to show the first one

divs.eq(0).hide(); // or to hide it

This example stores the wrapped set of elements that were matched in a variable. Then you pull out the ones you want using different jQuery methods. This way you don't need to continuously select the elements from the DOM.

As @Justus Romijn noted in a comment below, there are other methods like .first() to target a particular matched element, as well as selectors that can be used.

$("#hi div:first")

Which approach to take depends on the circumstance. Ultimately, it is good to avoid a repeated identical DOM selection. Since your first code seems to want to .hide() all the targeted divs, I'd store that in a variable, then pull from that collection as needed (like in my first example).

Upvotes: 7

Andrew Jackman
Andrew Jackman

Reputation: 13966

$("#hi div").children(':first-child').show();

and you could chain

$("#hi div").hide().children(':first-child').show();

Upvotes: 0

Related Questions