0

How can I get the method eg: "background" of an Object/element from string "background"? JSFiddle Here is my method that looks kind of jQuery:

 var $ = function css(selector,myStyle,value){
    var p = document.querySelectorAll("selector");
    for(var i = 0; i<x.length; i++){
        //This Works
        x[i].style.background = "#0489B1";

        //This doesn't
        //x[i].style.myStyle = "#0489B1";
    }
}

How can I call it using?

$(".example","background","blue");
tika
  • 7,135
  • 3
  • 51
  • 82
  • 1
    And look at the allowed properties, it's not the same as css exactly - http://www.sitestepper.be/en/css-properties-to-javascript-properties-reference-list.htm – marko Jan 27 '15 at 18:48

3 Answers3

1

You're looking for indexer notation:

x[i].style[myStyle] = value;
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

You need to access it using box brackets and not the dot notation.

x[i].style[myStyle] = "#0489B1"

When you use the dot notation, it looks for a property named myStyle in the style object which doesn't exist.

When you use the brackets, the value in the myStyle parameter is resolved first and then the expression is evaluated.

BatScream
  • 19,260
  • 4
  • 52
  • 68
1

The object properties can be accessed with dot notation and with square brackets notation:

function $(selector,myStyle,value){
    var p = document.querySelectorAll(selector);
    for(var i = 0; i<x.length; i++){
        //This Works
        p[i].style[myStyle] = value;
    }
}

Annotated ECMAScript 5.1 11.2.1 Property Accessors

zb'
  • 8,071
  • 4
  • 41
  • 68