Javascript - Function that returns value of a CSS property

1

Good night (good morning or good afternoon) to everyone!

I need a function that returns the value of a css property. Here is my code:

CSS:

.teste{
    opacity: 0;
    display: none;
}

JavaScript:

function funcao(){
 var elemento = document.getElementById("teste");
  function css(el, estilo){
     alert(document.defaultView.getComputedStyle(el, null).estilo);
  }
    css(elemento, "display");
}


However this returns "Undefined", so I did the function with only 1 parameter, below: JavaScript:

function funcao(){
 var elemento = document.getElementById("teste");
  function css(el){
     alert(document.defaultView.getComputedStyle(el, null).display);
  }
    css(elemento);
}

In this case, it returns "none". The problem is that I will need to fetch the value of several properties of several classes, so the css (el, style) function would be perfect (if it worked and returned the "none" in the example), so I could use, for example: br>

css(teste, display);
css(teste, visibility);
css(testeDois, display);


The css () function only has the "alert" for me to test what it returns, in the end, when it is working it will not have the "alert", it will only return the property value of the class

Thank you all, hopefully, I have managed to be clear in my problem

Many thanks!

    
asked by anonymous 12.01.2017 / 03:34

3 answers

2

You can pass the style between brackets [estilo] :

var elemento = document.getElementById("teste");

function css(el, estilo){
   console.log(estilo+':', document.defaultView.getComputedStyle(el, null)[estilo]);
}

css(elemento, "display");
css(elemento, "width");
.teste {
  width: 10px;
  display: none;
}
<div id="teste" class="teste">

Even though it is an object, javascript allows you to access the property by passing it in brackets instead of using .

    
12.01.2017 / 12:34
0

I would like to thank everyone for the tremendous help you have given me, both the bracket solution and the eval solution perfectly suited my problem. It was great to have received two different solutions, both of which contributed positively to my knowledge. Thank you all!!! : D

    
13.01.2017 / 03:51
-1

I think I understand what you want. Have you tried using eval? Eval aims to transform your "String" into interpretable code into your browser. So, follow the adapted code:

function funcao(){
 var elemento = document.getElementById("teste");
  function css(el, estilo){
     alert(eval("document.defaultView.getComputedStyle(el, null)." + estilo));
  }
    css(elemento, "display");
}
    
12.01.2017 / 04:27