1

After scouring the forums, I've been trying to use window to turn a parameter entered as a string into a workable variable. Here we start with the target location in the p tag...

<p id="rent"></p>

Then I call the function using the parameter "rent" to obtain the variable rent.

var rent = 125;
function display(attribute) {
        document.getElementById(attribute).innerHTML = window.attribute;
    }
display("rent");

However it still returns "undefined" so I must be making a mistake in syntax. Any solutions?


Update: @Sidd has the right approach in changing it to window[attribute] but I still can't get it to work with object properties, for example if you call rent.amt.

1 Answer 1

1

You almost have it:

var rent = 125;
function display(attribute) {
    document.getElementById(attribute).innerHTML = window[attribute];
}
display("rent");

window.attribute looks for a variable called attribute instead.

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

4 Comments

did you test that out? Now it's giving me [object HTMLParagraphElement] instead of undefined. How do I get 125?
Also works on codepen. I think you might be using jsFiddle, which doesn't provide consistent access to the window variable.
Huh, it wasn't working before but I can now get it going with this simple code. What seems to be causing bugs is using this for an object. var rent = { amt: 125, }; function display(attribute) { document.getElementById(attribute).innerText = window[attribute]; } display("rent.amt");
I can confirm that the issue is related to objects because it is working without them.

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.