Jumpy
Jumpy

Reputation: 53

Jquery plugin getting DIV ID

I want to pass to a plugin the ID of the DIV that's calling it.

A solution is calling it like this:

$('#mydiv').myplugin({
        myproperty : $('#mydiv').attr('id') 
    });

But I'd like to do something like this:

$('.myclass').myplugin({
    myproperty : $(this).attr('id') 
});

But "this" is not referring to myclass element. Is there a way to obtain myclass id dinamically?

Upvotes: 2

Views: 178

Answers (1)

Pointy
Pointy

Reputation: 413707

The problem is that you're attempting to use "$(this)" before your "myplugin" code even runs. There's no direct way to do what you're doing, but this might work:

$('.myclass').each(function() {
  $(this).myplugin({property: $(this).attr('id')});
});

Doing it that way, you allow jQuery to set up a function call to your "each" handler, with each element matching the selector individually. In each call to that function, this will refer to one of the elements. You then can call your plugin using properties of that element in the function call.

Upvotes: 3

Related Questions