0

How can you reference a javascript object indirectly?

Suppose:

<div id="foo" data-munchy="bar" data-crunchy="baz">FooBar</div>

<script>
document.getElementById("foo").onclick = function() {
    tempVariable = 'munchy';
    console.log(this.dataset.tempVariable);
}
</script>

How can I access this.dataset.{someVariable}? In this case, this.dataset.tempVariable

Is it only possible using eval or window?

4
  • You want this.dataset[tempVariable]. Commented Apr 27, 2018 at 19:21
  • 1
    this.dataset[tempVariable] for your example is the same as this.dataset.munchy. Commented Apr 27, 2018 at 19:21
  • 1
    Possible duplicate of Dynamically access object property using variable Commented Apr 27, 2018 at 19:27
  • @lealceldeiro it appears to be. I don't know why I had so much trouble finding it. Maybe the wording of the question isn't relatable to people who aren't familiar with the concept. Commented Apr 28, 2018 at 3:41

1 Answer 1

4

Use square bracket notation:

this.dataset[tempVariable];

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

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

2 Comments

@VictorStoddard - no, that will look for the string tempVariable - literally what OP originally had: this.dataset.tempVariable
This is great. I didn't realize they could be accessed both properties and arrays. Thanks, @Kevin.

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.