jonagoldman
jonagoldman

Reputation: 8754

How to get the ID of the div the function was called from in jQuery?

I have a jquery function ('rater') that I call this way:

<div id="someID"></div>

<script type="text/javascript">
    $('#someID').rater({options});
</script>

I want to get the ID ('someID' in this case) so then I can use it inside the function as a variable.

Then I use it in something like this:

if (??? == 'someID') { do something }

How can I do it??

Upvotes: 0

Views: 276

Answers (5)

John
John

Reputation: 11

This will look for the closest "div" called, then get its attribute.

if ($(this).closest("div").attr("id") == "someId") {
    // do stuff
}

Upvotes: 1

sqram
sqram

Reputation: 7201

if( $(this).attr('id') == 'someID' ) {
  // do stuff
}

Upvotes: 0

Nosredna
Nosredna

Reputation: 86216

Are you looking for selector?

After reading your edited question again, it sounds as though you want the string of the id passed through.

<div id="someID"></div>

<script type="text/javascript">
    $("#someID").rater({options},$("#someID").selector);
</script>

For efficiency sake, you can store the $("#someID") off in a variable if you like so you only do the query once.

Upvotes: 1

James
James

Reputation: 111910

Retrieving the selector used to call the plugin:

jQuery.fn.myPlugin = function() {
    alert( this.selector );
};

You can access the selector as a property of the jQuery object.

So, if I called the plugin like this:

$('div #something').myPlugin();

Then "div #something" would be alerted.


Retrieving an element's ID from within a plugin:

jQuery.fn.myPlugin = function() {
    alert( this.attr('id') );
};

Upvotes: 5

Shog9
Shog9

Reputation: 159618

Not sure why you're trying to do this, but...

// create jQuery plugin method: "rater"
jQuery.fn.rater = function() 
{
  // `this` is a jQuery object: process each matched element
  return this.each(function()
  {
    // `this` is a single matched element. Process it, somehow...
    if ( this.id == "someID" )
    {
      // do something special
    }

    // normal rater logic, whatever that might be
  });
};

Upvotes: 4

Related Questions