Today I came across this in some code:
$($($(this).children()[1])).css("border-color", "#fff");
I haven't seen this before, and to the best of my understanding, writing the following will accomplish the same thing:
$(this).children()[1].css("border-color", "#fff");
Is there any purpose to the top way (is it better?), or is this just someone now knowing what they are doing with JQuery?
The second expression won't do the same thing, because accessing array elements of a jQuery collection returns the DOM node, not a jQuery object, and you can't call jQuery methods on it. The actual equivalent would be:
$(this).children().eq(1).css("border-color", "#fff");
The first code is equivalent to:
var temp = $(this).children()[1]; // Get DOM node of 2nd child
$(temp).css("border-color", "#fff"); // Wrap it in jQuery object and set CSS
The only reason in the first example it's that [0] returns from the array the '0' indexed element out of the jQuery objects array (AKA: collection).
$('p')[0].hide(); // will NOT work
([0] is the JS getter from array, something like .get() method in jQuery)
that's why it's wrapped again inside a jQuery object function
$( $('p')[0] ).hide(); // Hides the '0' <p> element
You can also wrap jQ objects into additional objects*
$( $( $( $( $('p') ) ) ) ).hide();
*which is unneded, redundand , slow, Wrong in any case
Resume:
$( $('p')[0] ).hide(); // WORKS! cause the JS HTMLelement is
// again wrapped into an jQ Object
$( $('p').get(0) ).hide(); // WORKS (same reason)
$('p')[0].hide(); // WRONG! returns the unoperable (by jQ) JS Object
// HTMLelement, not a jQuery object
$('p').get(0).hide(); // WRONG! (same reason)
$( $( $( $( $('p')[0] ) ) ) ).hide(); // WTH?!
Playground: http://jsbin.com/enawup/3/edit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With