4

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 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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">

2 Comments

Thanks for helping, but that does not appear to return the parent element ?
You need this <div id="test"> to be your output?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.