Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created September 3, 2010 19:04
Show Gist options
  • Save rwaldron/564374 to your computer and use it in GitHub Desktop.
Save rwaldron/564374 to your computer and use it in GitHub Desktop.
// FROM:
// http://www.quora.com/Is-there-a-way-for-jQuery-to-return-a-single-object-instead-of-an-array-of-objects-For-example-if-I-use-an-id-selector#ans94625
// This is actually a good thing
var foo = $("#foo")
// but it's important to indicate that
// this var is a collection, and should
// be declared as:
//
// var $foo = $('#foo')
// This is a patently bad thing
$(foo).addClass("bar");
// that should've been down like this:
foo.addClass("bar");
// Because `foo` is ALREADY a jQuery collection
// and doesn't need to go through the system again.
// And if we're sticking to best practices, it
// really should've looked like this:
//
// $foo.addClass("bar");
// FROM:
// http://www.quora.com/Is-there-a-way-for-jQuery-to-return-a-single-object-instead-of-an-array-of-objects-For-example-if-I-use-an-id-selector
// This will only have one item in the collection...
$('#an_id');
// And will look like this if inspected:
>>> [ 'element#an_id' ]
// This may have a variable number of elements...
$('.a_class');
// And will look like this if inspected:
>>> [ 'element#a.a_class','element#c.a_class','element#c.a_class' ]
// Note that our matches each have a unique id: a, b and c
// But jQuery doesn't care, because
// it has normalized the handling
// of all collections
// This will add/set an attribute on all
// items in the collection. Which just happens
// to be only one item
$('#an_id').attr({
'data-foo' : "I've been data-foo'ed"
});
// This will add/set an attribute on all
// items in the collection. Which is 3 items
// in our example, but can be any number
$('.a_class').attr({
'data-foo' : "I've been data-foo'ed"
});
// I can get that attribute:
$('#an_id').attr('data-foo');
>>> "I've been data-foo'ed"
$('.a_class').attr('data-foo');
>>> "I've been data-foo'ed"
// But that only returned the attribute value of
// the element in the collection: 'element#a.a_class'
// if I want a specific element, I can use :eq(2)
// which return the collection, with only 1 item in it.
// The item returned is the whatever was found at index 2...
$('.a_class:eq(2)').attr('data-foo');
// or...
$('.a_class').eq(2).attr('data-foo');
/// ... in this case, if we look at just the collection:
$('.a_class:eq(2)');
// or..
$('.a_class').eq(2);
// It will look like this:
>>> [ 'element#c.a_class' ]
// This all works both ways for getters and setters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment