Reputation: 109
I have this simple bit of code:
var recipes = document.getElementsByClassName("recipes");
var recipesStyle = window.getComputedStyle(recipes, null);
It returns this error message:
Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
I have no idea what I'm doing wrong here. Can anyone help?
Upvotes: 3
Views: 17159
Reputation: 1075159
The error message is telling you exactly what's wrong: recipes
isn't an element (it's a collection of elements).
If you want the styles associated with the first recipe element, either add [0]
:
var recipes = document.getElementsByClassName("recipes");
var recipesStyle = window.getComputedStyle(recipes[0], null);
// Here ------------------------------------------^
...use querySelector
, which will just return the first element matching a given CSS selector:
var recipe = document.querySelector(".recipes");
var recipesStyle = window.getComputedStyle(recipe, null);
Or if you wanted to deal with the styles of each recipe element, you might use a loop:
var recipes = document.getElementsByClassName("recipes");
for (var n = 0; n < recipies.length; ++n) {
var thisRecipesStyle = window.getComputedStyle(recipes[n], null);
// ...
}
Upvotes: 7