2016-12-20 5 views
-2

Warum ich Fehler bekommen „canvas.setAttribute ist keine Funktion“, wenn ichWarum erhalte ich Fehler „canvas.setAttribute ist keine Funktion“

document.getElementsByClassName("canvas");

verwendet, aber wenn geändert

document.getElementById("canvas1");

es funktioniert gut.

Code:

(function setCanvas() { 
    var canvas = document.getElementsByClassName("canvas"); 
    var x = 250; 
    var y = 250; 
    // set width and height of canvas 
    canvas.setAttribute("style", "height:" + x + "px;" + " width:" + y + "px;"); 

    console.log("canvas width " + y); 
    console.log("canvas height " + x); 
}()); 
+0

Hinweis 's' in Methodenname -' getElements' - es gibt Array zurück ... – pwolaq

Antwort

3

getElementsByClassName gibt eine Liste von Elementen, nicht ein einziges Element.

1

getElementByClassName Rückgabe Array Typ; Verwenden Sie diesen Code:

(function setCanvas() { 
    var canvas = document.getElementsByClassName("canvas"); 
    var x = 250; 
    var y = 250; 
    // set width and height of canvas 
    canvas[0].setAttribute("style", "height:" + x + "px;" + " width:" + y + "px;"); 

    console.log("canvas width " + y); 
    console.log("canvas height " + x); 
}()); 
Verwandte Themen