Why window.innerheight/ window.innerWindow does not work with Document.getelementsbytagname('canvas');

Asked

Viewed 197 times

2

Why doesn’t it work?

const canvas = document.getElementsByTagName('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight

And that’s what?

const canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight

2 answers

3

Because getElementsByTagName returns a list of elements, if you want to take some property of the first element, you have to use:

const canvas = document.getElementsByTagName('canvas');
canvas[0].width = window.innerWidth;
canvas[0].height = window.innerHeight;

Or

const canvas = document.getElementsByTagName('canvas')[0];
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

1


When you use the querySelector, it returns the first corresponding element, so you can change the properties, in the first case, as mentioned in the other answer, it returns a list of elements, and the access is done through the index.

 const canvas = document.querySelector('canvas');

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

Browser other questions tagged

You are not signed in. Login or sign up in order to post.