0

I am building a jQuery Plugin which gets applied on a container element like that.

$('#container').myPlugin();

In this plugin I am trying to get the same element from another page trough .get().

$.get('page.php', function(data) {
    data = $.parseHTML(data);
    data = $('<div/>').html(data);

    data = data.find( myContainer );

}, 'html');

The problem is the myContainer-variable. I need the CSS-selector, which was applied to my plugin, is there any way I can get it?

I have found this solution, but it seems fairly complex. Maybe there is an easier solution especially for my case (plugin not object)?!

I could use another option in my plugin to get the selector, but I would like to avoid it, since it would feel like doubled information for the user. (Applying the plugin to the container and reference it in options).

Community
  • 1
  • 1
Afterlame
  • 1,188
  • 2
  • 13
  • 32

2 Answers2

0

I would use data-* attribute:

<a href="/resource" data-target="#element"></a>

Then you can read the value easily in your plugin context using jQuery .data('target') method. Using selector is not a flexible solution, there are many cases that the logic will fail. Adding an useful/important attribute to the element doesn't make the markup dirty.

Ram
  • 143,282
  • 16
  • 168
  • 197
  • I think, I don’t quite understand it. If I would add a `data`-attribute to my container, this would require another action from the user and I can’t add it from inside the plugin, since I would need to know the selector, used for the element, my Plugin has been applied on. – Afterlame Feb 21 '14 at 15:50
0

Ok, I think I found a solution:

var mySelector = $(this).selector

seems to work.


Important
.selector has been deprecated in jQuery 1.7 and was removed in jQuery 1.9.

Afterlame
  • 1,188
  • 2
  • 13
  • 32
  • 1
    Note that `selector` property was deprecated in jQuery 1.7 and removed in jQuery 1.9. – Ram Feb 21 '14 at 15:26
  • Hm I am using it in jQuery 1.11.0 and it seems to work. Has it been deprecated without any replacement? – Afterlame Feb 21 '14 at 15:29