0

I need a function, that changes the value of a passed attribute. You find an non-functioning example below. How do I have to pass the attribute and access the parameter? Thank you in advance!

let top = {target: document.getElementById("header").style.top};

animate(top, 50);



function foo(attribute, value) {

        //some code

        attribute.target = value + "px";

}

2 Answers2

1

Why not passing the element as argument directly?

let header = document.getElementById("header");

foo(header, 'top', 50);

function foo(element, attribute, value) {
  //some code

  element.style[attribute] = value + "px";
}

I've made the code on the fly, but you get the idea, right?

Hope it helps.

nahuelhds
  • 502
  • 4
  • 17
0

You cannot pass refences to primitives like Strings, Numbers and Booleans. You can, though, pass references to objects, in your example the DOM element:

let [top, attr, subAttr] = [document.getElementById("header"), "style", "top"];

foo(top, 50, attr, subAttr);

function foo(element, value, attr, subAttr) {
    if (subAttr) {
        element[attr][subAttr] = value+"px";
    else {
        element[attr] = value+"px";
    }
}
connexo
  • 53,704
  • 14
  • 91
  • 128
  • You also can't redefine `top` at least not in Chrome and Safari. – Mark May 10 '19 at 21:58
  • Thank you! But can I pass "style.top" separately? – Moritz Ferdinand Rocker May 10 '19 at 22:07
  • You could pass it as an array ["style", "top"] or use the String "style.top" and do split(".") in the function that handles it. – connexo May 10 '19 at 22:09
  • Added an example how to pass those additional parameters. – connexo May 10 '19 at 22:23
  • 1
    @connexo open the console and type: `let top = 1` ==> `SyntaxError: Can't create duplicate variable that shadows a global property: 'top'` You can use `var top = 1` without error, but it won't actually do anything. – Mark May 10 '19 at 22:26
  • Well, you cannot do it at global scope. You can, though, do it locally scoped. Is anybody still doing anything globally scoped? – connexo May 10 '19 at 22:28