Jquery Get parent element from data function

Viewed 59

I need to get the parent element of a dataset function, but can't seem to figure it out.

<div id="test">

$('#test').data('func', {
  me: function() {
   console.log(this.parent())
  }
})

$('#test').data('func').me();

what I would like to return is <div id="test">

Of course, this does not work, but is this possible?

2 Answers

The this in your stored object loses the context of the initiating jQuery object and points, rather, to itself.

this, in the context of your .data() object, looks like:

{
  me: function() {
   console.log(this.parent())
  }
}

Your object doesn't inherit the jQuery prototype, so it does not have a .parent() method. And there isn't a clean way of getting — or providing — reference to the $('#test') from inside the .data() structure.

You can work around that — again, not as elegantly as you had wanted — by providing some sort of reference to $('#test') when you create the .data()…

$('#test').data('func', {
  $el: $( '#test' ),
  me: function() {
   console.log( this.$el[0] );
  }
});

This will get you the <div id="#test"> element; at the cost of being dependent on explicitly referencing the element with each instance.

$('#test').data('func', {
  $el: $( '#test' ),
  me: function() {
   console.log( this.$el[0] );
  }
});

$('#test').data('func').me();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"></div>

Yes that is possible. You need to add the keyword this as $(this)

$('#test').data('func', {
  me: function() {
   console.log($(this).parent())
  }
})

$('#test').data('func').me();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">

Related