Jochen
Jochen

Reputation: 1776

JQuery bind event to collection item

I am able to bind events to all elements of a collection using JQuery. Anyway, if I want to pick just one item of the collection, no event is bound to it. In the upcoming code snippet there must be a mistake. Thanks in advance!

var divs = jQuery('.elternklasse').get(0).bind('click', function(){
    alert('Bin da');
});

Upvotes: 1

Views: 403

Answers (2)

David Thomas
David Thomas

Reputation: 253416

Use eq():

var divs = jQuery('.elternklasse').eq(0).bind('click', function(){
    alert('Bin da');
});

JS Fiddle demo.

To attach to an event to a specific range of elements, you could use :gt() or :lt():

var divs = $('div:gt(3)').bind('click', function(){
    alert('Bin da');
});​

JS Fiddle demo.

var divs = $('div:lt(3)').bind('click', function(){
    alert('Bin da');
});​

JS Fiddle demo.

Or to attach events to an arbitrary range of elements between two known points in the array of elements, use slice():

var divs = $('div').slice(3,6).bind('click', function(){
    alert('Bin da');
});​

JS Fiddle demo.

The above will trigger the click event on elements from index-point 3 until, but not including, 6.

References:

Upvotes: 3

Anthony Grist
Anthony Grist

Reputation: 38345

The .get() function returns the actual DOM element, not a jQuery object, so you can't call jQuery functions on it. You'll need to use the .eq() function instead, which will reduce the set to only the element at that position.

Upvotes: 0

Related Questions