I need to do this myself with TypeScript

-1

I have the following code in the java script and it works perfectly but I need to pass it to ionic with typescrpt and it does not store the array.

I do not know how to work the document.getElementsByClassName ('movil'); element in typeScript

var piezas = document.getElementsByClassName('movil');

for(var i=0;i<piezas.length;i++){
    piezas[i].setAttribute("width", tamWidh[i]);
    piezas[i].setAttribute("height",tamHeight[i]);
    piezas[i].setAttribute("x", Math.floor((Math.random() * 10) +1));
    piezas[i].setAttribute("y", Math.floor((Math.random() * 409) +1));
    piezas[i].setAttribute("onmousedown","seleccionarElemento(evt)");
}
    
asked by An3Ramirez 24.01.2018 в 05:52
source

1 answer

1

TypeScript is a superset type of JavaScript and getElementsByClassName works without problems. On the other hand, the code you share has "errors" that will make TypeScript not compile. I recommend that you go to the TypeScript test area to test the code.

You will automatically see errors :

  • tamWith is not defined (this is surely a false positive).
  • tamHeight is not defined (this is surely another false positive).
  • setAttribute requires that the last parameter be of type String, but with Math.floor((Math.random() * 10) +1) you are assigning a Number.
  • setAttribute requires that the last parameter be of type String, but with Math.floor((Math.random() * 409) +1) you are assigning a Number.
  • The solution would then be to define the variables tamWith and tamHeight (which I imagine are already defined, but not included in the shared snippet, just make sure that tamWith is correct and not tamWidth ), and pass a String instead of a number to setAttribute , something you can do using toString .

    Correcting that, the code is already works and compiles without errors :

    var piezas = document.getElementsByClassName('movil');
    var tamWidh = [];
    var tamHeight = [];
    
    for(var i=0;i<piezas.length;i++){
        piezas[i].setAttribute("width", tamWidh[i]);
        piezas[i].setAttribute("height",tamHeight[i]);
        piezas[i].setAttribute("x", Math.floor((Math.random() * 10) +1).toString());
        piezas[i].setAttribute("y", Math.floor((Math.random() * 409) +1).toString());
        piezas[i].setAttribute("onmousedown","seleccionarElemento(evt)");
    }
    
        
    answered by 25.01.2018 / 14:25
    source