holyredbeard
holyredbeard

Reputation: 21248

How to add different events to different divs

When using document.getElementsByTagName('div') you get an array of the div nodes, which can be used in a loop to assign different events to different divs.

How can I do this with jQuery?

Upvotes: 2

Views: 82

Answers (5)

Samich
Samich

Reputation: 30145

You can do the same in the jquery:

$('div').each(function() {
    if ($(this).attr('id') == '1')
       $(this).click(function() { // handler for first div });

    if ($(this).attr('id') == '2')
       $(this).click(function() { // handler for second div });\

    ...
});

Upvotes: 2

Praveen Prasad
Praveen Prasad

Reputation: 32117

var divs = jQuery('div');

divs.each(function(){
     $(this).DoSomeThing();

     // $(this) refers to a div
});

Upvotes: 0

jabclab
jabclab

Reputation: 15042

To do that in jQuery use:

$("div").each(function () {
    // 'this' is the div
});

This is the same as:

var divs = document.getElementsByTagName('div'),
    i,
    len,
    div;

for (i = 0, len = divs.length; i < len; i++) {
    div = divs[i];
}

Upvotes: 5

Manse
Manse

Reputation: 38147

$('div')

This will create a jQuery collection of DIVs Docs

Upvotes: 0

Mike Sav
Mike Sav

Reputation: 15311

Just add the name into jQuery's selector...

$("tag-name-here")

You can then use .each, however for performance I prefer to use a good old Javascript for loop.

This may help: http://api.jquery.com/each/ & http://jquery-howto.blogspot.com/2009/06/javascript-for-loop-vs-jquery-each.html

Upvotes: 0

Related Questions